python - Find model object that encompasses another in Django -
given unsaved/local model object, how can find list of objects have information of unsaved object without having keep list of fields in sync?
for example, have model:
class person(models.model): name = models.charfield(max_length=100) job = models.charfield(max_length=100, null=true) hands_lost = models.integerfield(null=true)
and have created data in past this:
person.objects.create(name='luke', job='trainee') person.objects.create(name='yoda', job='master') person.objects.create(name='yoda', job='force ghost')
and 'hands lost in universe' db event telling me "set luke's hands_lost 1", like:
luke = find_my_object(person(name='luke')) if luke: luke.hands_lost = 1 luke.save() else: luke = person.objects.create(name='luke', hands_lost=1)[0]
where:
def find_my_object(person): return **magic here**.first()
expected results might be:
find_my_object(person(name='luke')) -> luke find_my_object(person(name='yoda')) -> 1st yoda find_my_object(person(name='yoda', job='force ghost')) -> 2nd yoda
a possible implementation suffers 'keep list of fields in sync' problem be:
def find_my_object(person): query = {} field in ['name', 'job', 'hands_lost']: value = getattr(person, field) if value: query[field] = value return person.objects.filter(**query).first()
following questions:
- is pointless exercise, should keep data coming outside dictionary long possible?
- what if
person
has related field might want include? e.g.side = models.foreignkey(sideoftheforce, null=true)
is pointless exercise
yes, not reasons you've stated dictionary
it appear me obfuscating code sake of when same can achieved inserting queryset expect introduce new method.
you're not achieving abstracting call since still need pass in same information without method.
for worth, update_or_create
may able example code given.
Comments
Post a Comment