筛选通用外键

斯蒂芬

有没有更多的“ Python / Django”方法可以通过通用外键查询/过滤对象?我正在尝试获取特定软件的所有FullCitation对象,其中is_primary为True。

我知道我做不到,但我想做这样的事情:

ct_supported = ContentType.objects.get(app_label="supportedprogram", model="software")
primary_citations = FullCitation.objects.filter(content_type__name=ct_supported, object_id__in='', is_primary=True)

models.py

class FullCitation(models.Model)
    # the software to which this citation belongs
    # either a supported software program or a non-supported software program

    limit = models.Q(app_label = 'myprograms', model = 'supportedprogram') | models.Q(app_label = 'myprograms', model = 'nonsupportedprogram') 
    content_type = models.ForeignKey(ContentType), limit_choices_to = limit, )
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    is_primary = models.BooleanField(help_text="Is this the Primary Citation for the software program?")

class NonSupportedProgram(models.Model):
    title = models.CharField(max_length=256, blank = True)
    full_citation = generic.GenericRelation('FullCitation')

class SupportedProgram(models.Model):
    title = models.CharField(max_length=256, blank = True)
    full_citation = generic.GenericRelation('FullCitation')
    # and a bunch of other fields.....

views.py#我目前的尝试

primary_citations = []
sw_citations = sw.full_citations.all()
    for x in sw_citations:
        if x.is_primary:
            primary_citations.append(x)
洪水

理解应该是筛选QuerySet的最后手段。最好让它们尽可能长地保留为QuerySet。我认为这是您要寻找的:

ct_supported = ContentType.objects.get_for_model(SupportedProgram))
primary_citations = FullCitation.objects.filter(content_type=ct_supported, is_primary=True)

更新:如果要筛选特定的SupportedProgram实例,请执行以下操作:

my_supported = SupportedProgram.objects.get(id=instance_id_goes_here)
ct_supported = ContentType.objects.get_for_model(SupportedProgram))
primary_citations = FullCitation.objects.filter(content_object=my_supported, content_type=ct_supported, is_primary=True)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Django通用外键

来自分类Dev

Django通用外键排序

来自分类Dev

筛选外键对象中的> 10个条目

来自分类Dev

具有多个查询参数和外键的DRF筛选

来自分类Dev

筛选外键对象中的> 10个条目

来自分类Dev

Django:筛选查询集并选择结果外键

来自分类Dev

Django无法级联删除相关的通用外键对象

来自分类Dev

Django:使用通用外键链接两个模型

来自分类Dev

LinqToSQL外键实体到字符串的通用查找

来自分类Dev

Django Deliciouspie,包括通用外键字段结果

来自分类Dev

SQL外键外键

来自分类Dev

Django通用外键过滤(v1.5和v1.6之间的差异)

来自分类Dev

通用错误1215:无法为Laravel 5添加外键约束

来自分类Dev

将通用视图中的queryset限制为具有request.user作为外键的对象

来自分类Dev

Django通用外键过滤(v1.5和v1.6之间的差异)

来自分类Dev

我应该在Django中使用通用外键吗?如何使用?

来自分类Dev

如何在通用外键中生成content_type_id的值?

来自分类Dev

如何提供正确的请求正文来序列化 Django 通用外键?

来自分类Dev

外键与辅助键

来自分类Dev

通用存储库GetAll筛选器不筛选

来自分类Dev

外键上的外键-SQL Server

来自分类Dev

带有Django REST API和generic_relations的ValidationError,用于通用外键可写访问

来自分类Dev

外键还是复合键?

来自分类Dev

重复外键

来自分类Dev

如何制作外键?

来自分类Dev

Django ::参考外键

来自分类Dev

MySQL创建外键

来自分类Dev

MySQL外键设置

来自分类常见问题

非主键的外键