python - _meta.get_all_field_names() 中的 GenericForeignKey 名称错误

标签 python django

我有两个模型:

class First(models.Model):
    name = models.CharField(max_length=50, default='n/a')
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()


    def __unicode__(self):
        return str(self.pk) + ' > ' + self.name


class Second(models.Model):
    name = models.CharField(max_length=50, default='n/a')
    r = generic.GenericRelation(First)

    def __unicode__(self):
        return str(self.pk) + ' > ' + self.name

当我这样做时:

from myapp.models import First
First._meta.get_all_field_names()

我得到:

['content_type', u'id', 'name', 'object_id', 'second']

所以看起来这里的 GenericForeignKey 不是 content_object,而是名为 second。这是预期的行为吗?

ps
我使用的是 Django 1.5.1。

最佳答案

GenericForeignKey 在幕后使用两个字段;在本例中,它们是 content_typeobject_id,因为 those are the default names第二个created by the GenericRelationSecond.r上。

关于python - _meta.get_all_field_names() 中的 GenericForeignKey 名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17028886/

相关文章:

python - 生成联合分发列表

django - celery 执行计划任务一百次

python - 有类似于微 Controller 中断处理程序的东西吗?

python - 如何使用 Jinja2 打印表格(无需页面刷新)

python - Django Apache 2 ModuleNotFoundError : No module named 'django'

python - 如何将 GenericRelation 与 Django Rest Framework 一起使用?

python - Django 从模板中带有 for 键值的字典中获取特定值

django模型形式,根据ForeignKey模型中的值限制选择

python - 将 for 循环写入列表理解

python - 将(截图捕获的)图像转换为 Base 64,而不在 python 中保存为 png/jpeg