标签: generic-foreign-key

django:我如何根据GenericForeignKey的字段进行查询?

我是使用GenericForeignKey的新手,我无法使它在查询语句中工作.表格大致如下:

class Ticket(models.Model):
    issue_ct = models.ForeignKey(ContentType, related_name='issue_content_type')
    issue_id = models.PositiveIntegerField(null=True, blank=True)
    issue = generic.GenericForeignKey('issue_ct', 'issue_id')

class Issue(models.Model):
    scan = models.ForeignKey(Scan)
Run Code Online (Sandbox Code Playgroud)

扫描会产生一个问题,一个问题会产生一些故障单,我将问题作为Ticket表的外键.现在我有一个Scan对象,我想查询与此扫描相关的所有故障单.我先试了一下:

tickets = Tickets.objects.filter(issue__scan=scan_obj)
Run Code Online (Sandbox Code Playgroud)

这不起作用.然后我尝试了这个:

issue = Issue.objects.get(scan=scan_obj)
content_type = ContentType.objects.get_for_model(Issue)
tickets = Tickets.objects.filter(content_type=content_type, issue=issue)
Run Code Online (Sandbox Code Playgroud)

仍然无法正常工作.我需要知道如何在django中进行这些查询?谢谢.

django generic-foreign-key

45
推荐指数
2
解决办法
2万
查看次数

Django:使用contenttypes框架的泛型关系的例子?

我已经多次仔细研究了关于contenttypes框架的Django文档,而我根本不理解它在我的项目中实现泛型关系.我已经找到了有关此事的在线示例或教程,但我找不到一个.叫我笨,但我需要一些帮助(请不要简单地链接到文档).基于在线资源的缺乏,我相信如果你用一个详尽的例子回答这个问题,你的答案可能是迄今为止关于django泛型关系的最有用的例子(奖金!).

所以,我的问题是:有人可以展示一个简单的模型示例,也许还有几行代码显示如何与泛型模型的实例进行交互?


作为灵感,我认为这是一个非常常见的情况:

一个站点的媒体项目在很大程度上被视为相同,但略有不同.例如,假设有图像和视频项目,用户可以"喜欢"项目或"注释"项目.喜欢和评论应该被视为相同,无论它们是张贴在图像还是视频项目上.因此,如果有用于查看用户相册中的图像或视频的ItemView,则可以进行以下类型的调用:mediaitem.comments.all()或者,len(mediaitem.likes.all())或者comment.user_who_commented,无需知道它是哪种媒体项(图像或视频).

我相信你需要六种型号:

  • 抽象MediaItem
  • 两种不同类型的媒体项目:ImageItemVideoItem
  • 抽象MediaItemActions
  • 可以对媒体项目执行的两种不同类型的操作:LikeComment

如果您知道如何使用这个Django功能,请向我们展示一个完整的示例!我觉得这将是一个非常强大的工具,我很想在我的应用程序中使用它.越明确越好.

python django django-models django-contenttypes generic-foreign-key

21
推荐指数
1
解决办法
6868
查看次数

删除时为什么我的GenericForeignKey级联不会?

我正在创建一个自定义评论系统,可以使用contenttypes GenericForeignKey将评论附加到任何模型.

class Comment(models.Model):
    body = models.TextField(verbose_name='Comment')
    user = models.ForeignKey(User)
    parent = models.ForeignKey('self', null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
Run Code Online (Sandbox Code Playgroud)

我的理解是,当附加注释的模型被删除时,删除应该级联并删除注释.

不幸的是,这没有发生,我很难过.是否有任何常见原因可以更改默认删除行为?

django foreign-keys cascading-deletes django-contenttypes generic-foreign-key

20
推荐指数
2
解决办法
4698
查看次数

django:预取GenericForeignKey的相关对象

假设我有一个模型,Box一个GenericForeignKey指向任何一个Apple实例或Chocolate实例.AppleChocolate反过来,有ForeignKeys来FarmFactory,分别.我想显示一个Boxes 列表,我需要访问FarmFactory.如何在尽可能少的数据库查询中执行此操作?

最小的说明性示例:

class Farm(Model):
    ...

class Apple(Model):
    farm = ForeignKey(Farm)
    ...

class Factory(Model):
    ...

class Chocolate(Model):
    factory = ForeignKey(Factory)
    ...

class Box(Model)
    content_type = ForeignKey(ContentType)
    object_id = PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    ...

    def __unicode__(self):
        if self.content_type == ContentType.objects.get_for_model(Apple):
            apple = self.content_object
            return "Apple {} from Farm {}".format(apple, apple.farm)
        elif self.content_type == ContentType.objects.get_for_model(Chocolate):
            chocolate = self.content_object
            return …
Run Code Online (Sandbox Code Playgroud)

django optimization foreign-keys generic-foreign-key

16
推荐指数
1
解决办法
5471
查看次数

sqlalchemy通用外键(如django ORM)

sqlalchemy有像django的GenericForeignKey吗?是否使用通用外国字段是正确的.

我的问题是:我有几个模型(例如,Post,Project,Vacancy,没什么特别的),我想为每个模型添加注释.我只想使用一个评论模型.值得吗?或者我应该使用PostComment,ProjectComment等?两种方式的利弊?

谢谢!

python django sqlalchemy generic-foreign-key

15
推荐指数
1
解决办法
2533
查看次数

如何使用GenericRelation的逆

我必须真正误解Django的内容类型框架中的GenericRelation字段.

要创建一个最小的自包含示例,我将使用教程中的民意调查示例应用程序.将通用外键字段添加到Choice模型中,并创建一个新Thing模型:

class Choice(models.Model):
    ...
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    thing = GenericForeignKey('content_type', 'object_id')

class Thing(models.Model):
    choices = GenericRelation(Choice, related_query_name='things')
Run Code Online (Sandbox Code Playgroud)

使用干净的数据库,同步表,并创建一些实例:

>>> poll = Poll.objects.create(question='the question', pk=123)
>>> thing = Thing.objects.create(pk=456)
>>> choice = Choice.objects.create(choice_text='the choice', pk=789, poll=poll, thing=thing)
>>> choice.thing.pk
456
>>> thing.choices.get().pk
789
Run Code Online (Sandbox Code Playgroud)

到目前为止一切都很好 - 关系在一个实例的两个方向上都有效.但是从查询集中,反向关系非常奇怪:

>>> Choice.objects.values_list('things', flat=1)
[456]
>>> Thing.objects.values_list('choices', flat=1)
[456]
Run Code Online (Sandbox Code Playgroud)

为什么反向关系再次给我一个id thing?我期待相当于选择的主键,相当于以下结果:

>>> Thing.objects.values_list('choices__pk', flat=1)
[789]
Run Code Online (Sandbox Code Playgroud)

那些ORM查询生成如下SQL:

>>> print Thing.objects.values_list('choices__pk', flat=1).query
SELECT "polls_choice"."id" FROM "polls_thing" …
Run Code Online (Sandbox Code Playgroud)

python sql django generic-foreign-key django-generic-relations

12
推荐指数
1
解决办法
562
查看次数

如何遍历Django中的GenericForeignKey?

我正在使用Django v1.9.4和PostgreSQL 9.2.14.使用以下型号:

from django.db import models
from django.contrib.contenttypes.fields import GenericRelation, GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Foo(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    bar = GenericForeignKey('content_type', 'object_id')

class Bar(models.Model):
    foos = GenericRelation(Foo, related_query_name='bars')
    class Meta:
        abstract = True

class BarX(Bar):
    name = models.CharField(max_length=10, default='bar x')

class BarY(Bar):
    name = models.CharField(max_length=10, default='bar y')
Run Code Online (Sandbox Code Playgroud)

创建一些实例来演示我的问题:

>>> bar_x = BarX.objects.create()
>>> bar_y = BarY.objects.create()
>>> foo1 = Foo.objects.create(bar=bar_x)
>>> foo2 = Foo.objects.create(bar=bar_y)
>>> foo1.bar.name
u'bar x'
>>> foo2.bar.name
u'bar y'
Run Code Online (Sandbox Code Playgroud)

我无法遍历django中的GFK,尝试过滤引发异常,并显示一条消息,建议添加GenericRelation …

python django postgresql generic-relations generic-foreign-key

11
推荐指数
1
解决办法
6061
查看次数

在 Model.Meta 中使用 CheckConstraint 和 Django GenericForeignKey 时出错 - 此查询中不允许加入字段引用

我试图限制 GFK 只指向几个模型的对象,我认为 CheckConstraint 将是一个很好的方法,但是我得到了这个错误

class ManualAdjustment(Model):
    content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField(null=True)

    booking_obj = GenericForeignKey('content_type', 'object_id')  
    # should point to a app1.Booking1 or app2.Booking2 or app3.Booking3 only - trying to enforce this via CheckConstraint


    class Meta:
        constraints = [
            models.CheckConstraint(
                check=
                Q(content_type__app_label='app1', content_type__model='booking1') |
                Q(content_type__app_label='app2', content_type__model='booking2') |
                Q(content_type__app_label='app3', content_type__model='booking3'),
                name='myconstraint_only_certain_models'),
        ]

Run Code Online (Sandbox Code Playgroud)

我在迁移时出错

    execute_from_command_line(sys.argv)
  File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/commands/sqlmigrate.py", …
Run Code Online (Sandbox Code Playgroud)

django generic-foreign-key django-postgresql django-migrations django-generic-relations

10
推荐指数
1
解决办法
847
查看次数

是否可以在Django中使用GenericForeignKey的自然键?

我有以下内容:

target_content_type = models.ForeignKey(ContentType, related_name='target_content_type')
target_object_id = models.PositiveIntegerField()
target = generic.GenericForeignKey('target_content_type', 'target_object_id')
Run Code Online (Sandbox Code Playgroud)

我想dumpdata --natural为这种关系发出一个自然的关键.这可能吗?如果没有,是否有一种替代策略不会将我绑定到目标的主键?

django natural-key generic-foreign-key

8
推荐指数
1
解决办法
1058
查看次数

Django Admin中的通用关系/通用外键

我一直在尝试在Django管理员中显示通用外键但无法使其正常工作.我有一个FullCitation类,可以链接到NonSupportedProgram或SupportedProgram类.所以,我使用了通用外键.

在管理员中,我希望用户只能从content_type下拉列表中选择"NonSupportedProgram"或​​"SupportedProgram",然后从object_id字段中,我需要用户能够从下拉列表中选择现有的NonSuportedPrograms或现有的支持的程序,可以选择创建新程序.这可能吗?我哪里错了?

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 Meta:
        unique_together = ('content_type', 'object_id')
        app_label = 'myprograms'

reversion.register(FullCitation)

class NonSupportedProgram(models.Model):
    title = models.CharField(max_length=256, blank …
Run Code Online (Sandbox Code Playgroud)

python django django-models django-admin generic-foreign-key

7
推荐指数
1
解决办法
1276
查看次数