【问题标题】:Django tastypie save reverse GenericForeignKeyFieldDjango sweetpie 保存反向 GenericForeignKeyField
【发布时间】:2013-12-26 23:35:06
【问题描述】:

Django Tastypie 即使是反向关系也可以保存相关对象。

但是 Django Tastypie 是否可以保存 GenericForeignKeyField 的反向关系?

我的资源(未满,但仅重要的),

class AreaResource(ModelResource):
    tripl3user = fields.ManyToManyField(
        'tripl3sales.api.resources.area.Tripl3UserResource',
        'tripl3user',
        related_name='area',
        full=True
    )

class Tripl3UserResource(ModelResource):
    content_type = fields.ForeignKey(
        'tripl3sales.api.resources.contenttype.ContentTypeResource',
        'content_type'
    )
    content_object = GenericForeignKeyField({
        Area : AreaResource
        }, 'content_object')

我的models.py

class Area(models.Model):
    name = models.CharField(max_length=50, unique=True)
    tripl3user = generic.GenericRelation('Tripl3User')

class Tripl3User(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

是否可以保存通用外键的反向关系?如果是这样,那该怎么做?数据是什么样的?

【问题讨论】:

    标签: django tastypie generic-foreign-key


    【解决方案1】:

    我终于得到了答案。

    在具有content_typeobject_id 的资源中,无需声明content_type,因为content_object 就足够了。而对于related_name,我们不使用area,而是使用content_object

    所以,我的 resources.py 应该是,

    class AreaResource(ModelResource):
        tripl3user = fields.ManyToManyField(
            'tripl3sales.api.resources.area.Tripl3UserResource',
            'tripl3user',
            related_name='content_object',
            full=True
        )
    
    class Tripl3UserResource(ModelResource):
        content_object = GenericForeignKeyField({
            Area : AreaResource
        }, 'content_object')
    

    希望这对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 2012-01-01
      • 1970-01-01
      • 2013-01-09
      • 2011-10-24
      相关资源
      最近更新 更多