pythondjangomodelnatural-key

Filtering by natural key?


I don't have the ids of the objects I want because they were created by bulk_create: and bulk_create doesn't return objects with ids so I need to fetch them by their natural keys.

Is it possible to fetch the objects by filtering by natural key? I've found nothing in the documentation.

We can already do:

id_list = [10,3,5,34]
MyModel.objects.filter(id__in=id_list)

I'd like the same thing with natural key:

NK_list = [('bob','carpenter'),('jack','driver'),('Leslie','carpenter')]
chosen_persons = Person.objects.filter(natural_key__in=NK_list)

My model looks like this:

class PersonManager(models.Manager):
    def get_by_natural_key(self, name, job):
        return self.get(name=name, job=job)

class Person(Models.model):
    name = models.CharField(max_length=200)  
    job = models.CharField( max_length=200)  

    objects = PersonManager() 


    class Meta:
        unique_together = [['name', 'job']]

    def natural_key(self):
        return (self.name, self.job)

--EDIT--

Eventually I've found a faster solution to get back the objects created by the bulk_created: Filter by the last created objects! I've compared the time between that and getting the objects by natural keys, and it's definitively faster.


Solution

  • You can do like:

    NK_list = [('bob','carpenter'),('jack','driver'),('Leslie','carpenter')]
    query = Q()
    for name, job in NK_list:
        query |= Q(name=name, job=job)
    
    chosen_persons = Person.objects.filter(query)