[英]Queryset containing related Object with same foreignkey
eg I've a person with an address例如我有一个有地址的人
class Persons(models.Model):
adress = models.ForeignKey(Adress, on_delete=models.DO_NOTHING, blank=True,
null=True)
class Adress(models.Model):
some_data = models.IntegerField()
and i have another related data in antoher model like this我在这样的另一个模型中有另一个相关数据
class Places(models.Model):
adress = models.ForeignKey(Adress, on_delete=models.DO_NOTHING)
how can i get a queryset now of both persons and places if adress is set in persons?如果地址设置为人员,我现在如何获得人员和地点的查询集?
You can obtain the Places
of a Persons
object with:你可以得到
Places
上Persons
与对象:
Places.object.filter(adress__persons=myperson)
If you want to do this in bulk, you can work with:如果您想批量执行此操作,您可以使用:
qs = Persons.objects.select_related('adress').prefetch_related('adress__places_set')
this will load the related Places
in bulk, so you can fetch these with:这将批量加载相关
Places
,因此您可以使用以下方法获取这些地点:
for person in qs:
print(person.adress.places_set.all())
You can do somethings like this but first you need to add related_name
in your Persons and Places Foreign key你可以做这样的事情,但首先你需要在你的 Persons 和 Places 外键中添加
related_name
class Persons(models.Model):
adress = models.ForeignKey(Adress,related_name = "persons_adress",on_delete=models.DO_NOTHING, blank=True,null=True)
class Adress(models.Model):
some_data = models.IntegerField()
class Places(models.Model):
adress = models.ForeignKey(Adress, related_name = "places_addres",on_delete=models.DO_NOTHING)
After this alteration you can now query在此更改后,您现在可以查询
Adress.objects.filter(persons_adress__some_data = some_data,places_addres__some_data = some_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.