Django: get ValueQuerySet with values from generic relation
I have two models linked by a generic relation:
from django.contrib.contenttypes import generic
from django.db import models
class Bar(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
code = models.CharField(max_length=10)
value = models.IntegerField()
class Foo(models.Model):
... base fields ...
bars = generic.GenericRelation(Bar)
and now I want to get all the 'bar.value's whose 'code is 'xxx', with a syntax like:
Foo.objects.filter(...foofilters..., bars__code='xxx').values('bars__value')
but this doesn't work (Django tells me that 'bars__value' is not a valid field).
Any hint?
EDIT: in SQL I would have done something like this:
SELECT bar.value
FROM foo
JOIN django_content_type AS ct
ON ct.app_label = 'foo_app'
AND ct.model = 'foo'
JOIN bar
ON bar.content_type_id = ct.id
AND bar.object_id = foo.id
WHERE bar.code = 'xxx'
开发者_如何转开发
or taking content_type_id with another query
You cannot do it like that... Imaging how sql should look like for that case
What you might need is:
foo_ids = Foo.objects.filter(foo-filters).values_list('id', flat=True) # Getting Foo ids filtered
Bar.objects.filter(
content_type=ContentType.objects.get_for_model(Foo),
object_id__in=foo_ids,
bar-filters
).values('value')
精彩评论