简体   繁体   中英

Selecting a related set of objects in Django

I have two models:

class ModelA(models.Model):
    name = models.CharField()

class ModelB(models.Model):
    a = models.ForeignKey(ModelA)
    value = models.CharField()

ModelB always belongs to a ModelA . I have a certain query that filters my ModelB s:

ModelB.objects.filter(value='foo')

From that QuerySet I need to retrieve the matching ModelA set. So I tried this:

>>> ModelB.objects.filter(value='foo').values('a')
[{'a': 2}, {'a': 4}, {'a': 6}]

But as you can see that only got me the object id s. How can I fetch the objects themselves?

如果需要ModelAs,则必须要求提供ModelAs。

ModelA.objects.filter(modelb__value='foo')

Currently I have this little number:

model_a_list = ModelB.objects.filter(value='foo').values('a')
ModelA.objects.filter(id__in=model_a_list)

Any better ways to do this would be much appreciated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM