[英]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.我没有我想要的对象的 id,因为它们是由bulk_create
创建的:并且bulk_create
不返回具有 id 的对象,所以我需要通过它们的自然键来获取它们。
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:我的 model 看起来像这样:
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.最终,我找到了一个更快的解决方案来取回由bulk_created
创建的对象:按最后创建的对象过滤,我比较了这之间的时间和通过自然键获取对象的时间。 and it's definitively faster.而且它肯定更快。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.