问题描述
假设我有几个代表现实生活中的对象的模型:人,主席, Room我还有一个集合模型,代表这些模型的一些记录集。
每个模型都可以是多个集合的成员 - 因此,我还创建了一个成员资格模型,它表示一个对象是一个集合的成员。定义如下:
class Membership(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type','object_id')
collection = models.ForeignKey('Collection',related_name =成员)
我想要创建一个 QuerySet 给定一个集合,表示给定模型的所有成员 。我知道我可以以编程方式执行,但是我需要一个QuerySet,它可以被过滤,订购等。
编辑: p>
显然,这可以使用原始SQL:
SELECT * FROM
(modelx INNER JOIN membership ON modelx.id = membership.object_id)
WHERE
(membership.collection_id =< my-collection-id> AND
membership.content_type_id = modelx-type-id>)
但是可以使用Django查询语言来表示? >
似乎我已经找到了解决方案,通过使用 QuerySet
的 extra
方法:
def members_of_model(collection,cls):
cls_type = ContentType.objects.get_for_model(cls)
cm_tablename = CollectionMembership._meta.db_table
cls_tablename = cls._meta.db_table
return cls.objects.all()。extra(tables = [cm_tablename],
其中= ['%s.content_type_id = %% s'%cm_tablename,
'%s.collection_id = %% s'%cm_tablename,
'%s.object_id =%s.id'%(cm_tablename,cls_tablename)],
params = [cls_type.id,collection.id])
这将返回一个特定模型的有效QuerySet,它包含作为特定集合成员的所有记录。
Suppose I have a few models representing real life objects: "Person", "Chair", "Room"
I also have a "Collection" model, which represents some collection of records of these models.
Each model can be a member of more than on collection - therefore, I have also created a "Membership" model, which represents an object is a member of a collection. It is defined as follows:
class Membership(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
collection = models.ForeignKey('Collection', related_name="members")
I want to be able to create a QuerySet, which given a collection, represents all its members of a given model. I know I can do it programmatically, but I need it in a QuerySet, which can be filtered, ordered etc.
EDIT:
Obviously this can be done using raw SQL:
SELECT * FROM
( modelx INNER JOIN membership ON modelx.id = membership.object_id)
WHERE
( membership.collection_id=<my-collection-id> AND
membership.content_type_id=<modelx-type-id> )
But can it be represented using the Django query language?
It seems I have found the solution, by using QuerySet
's extra
method:
def members_of_model(collection,cls):
cls_type = ContentType.objects.get_for_model(cls)
cm_tablename = CollectionMembership._meta.db_table
cls_tablename = cls._meta.db_table
return cls.objects.all().extra(tables=[cm_tablename],
where=[ '%s.content_type_id=%%s' % cm_tablename,
'%s.collection_id=%%s' % cm_tablename,
'%s.object_id=%s.id' % (cm_tablename, cls_tablename) ],
params=[cls_type.id,collection.id] )
This returns a valid QuerySet of a specific model, which holds all records which are members of a specific collection.
这篇关于Tricky Django GenericRelation查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!