相关疑难解决方法(0)

如何遍历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
查看次数