如何从序列化器中的父对象模型中获取字段 -​​ django rest框架

时间:2016-05-26 22:17:56

标签: python django django-rest-framework

我有两个模型..讨论扩展了GenericModel。

perl -nle '/0{15}|9{15}/ && print; s/([+-])0/$1\0000000000/ && s/      X/X/ && print' Inputfile.01.DAT

class GenericModel(models.Model):

content_type = models.ForeignKey(
    ContentType,
    on_delete=models.CASCADE
)

object_id = models.PositiveIntegerField()

content_object = GenericForeignKey('content_type', 'object_id')

class Meta:
    abstract = True

class Discussion(GenericModel):

author = models.ForeignKey(
    'auth.User'
)

name = models.CharField(
    max_length=200
)

description = models.TextField()

created_data = models.DateTimeField(
    default=timezone.now
)

comments = models.ManyToManyField(
    'discussions.Comment',
    default='',
    blank=True,
    related_name='discussion_comments'
)

is_closed = models.BooleanField(
    default=False
)

visits = models.IntegerField(
    default=0
)

def __str__(self):
    return self.name

所以..如果我在COMMON_FIELDS列表中放入'content_type','object_id','content_object',应用程序会将此错误返回给我:

COMMON_FIELDS = (
'pk',
'author',
'name',
'description',
'created_data',
'comments',
'is_closed',
'visits'
)


class DiscussionSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
    model = Discussion
    fields = COMMON_FIELDS


class DiscussionListSerializer(serializers.HyperlinkedModelSerializer):
comments = CommentSerializer(many=True)

class Meta:
    model = Discussion
    fields = COMMON_FIELDS

我该怎么做,或者解决此问题的更好方法是什么?

1 个答案:

答案 0 :(得分:0)

嗯,它是df8 <- as.data.frame(lapply(df8, function(X) unname(unlist(X)))) merge(df8, df8, by = c("V5")) str(df8, max.level = 1) ,您的序列化工具会尝试解析HyperlinkedModelSerializer上相关GenericModel的网址。

我认为解决方案是在Discussion上定义GenericModel字段以使用它(同时定义DiscussionSerializer/DiscussionListSerializer序列化程序)。这比尝试解析模型中未包含的内容的URL更好。有关处理嵌套对象的信息,请参阅序列化程序docs