我正在使用Django 1.7.1。
我有一组类似于以下结构的模型:
class Group(models.Model):
name = models.CharField(max_length=50, unique=True)
class ItemTypeOne(models.Model):
name = models.CharField(max_length=50, unique=True)
ref = models.ForeignKey(Group)
class ItemTypeTwo(models.Model):
name = models.CharField(max_length=50, unique=True)
ref = models.ForeignKey(Group)
class ItemTypeThree(models.Model):
name = models.CharField(max_length=50, unique=True)
ref = models.ForeignKey(Group)
如此处所述,我知道可以使用orm来过滤特定类的对象未指向的对象。在我的情况下,它将是这样的:
filtered = Group.objects.exclude(itemtypeone__isnull=False,
itemtypetwo__isnull=False,
itemtypethree__isnull=False)
我的目标是使用orm来获得相同的结果,而无需显式通知“反向关系”,类似于(伪代码如下):
filtered = Group.objects.exclude(gereric_reverse_relations_exp__isnull=False)
使用django orm可以实现吗?
提前致谢!:)
您可以检查所有模型以找出哪些模型具有外键Group
并动态构建查询。使用模型的_meta
get_all_related_objects()
列表来RelatedObject
获取您的Group
模型的列表:
>>> related = Group._meta.get_all_related_objects()
>>> print related
[<RelatedObject: app:itemtypeone related to group>, <RelatedObject: app:itemtypetwo related to van>, <RelatedObject: app:itemtypethree related to group>]
然后建立您的查询:
>>> excludes = dict(("%s__isnull" % ro.get_accessor_name(), False) for ro in related)
并执行查询:
>>> filtered = Group.objects.exclude(**excludes)
(警告:大多数未经测试的代码,可能需要进行一些调整)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句