如何将SlugRelated字段设置为对象字段中的字段

时间:2016-06-06 20:02:14

标签: django django-models django-rest-framework

我有以下型号:

class Category(models.Model):
    name = models.CharField()
    ... # fields omitted

class Prediction(models.Model):
    conversation = models.ForeignKey(Conversation)
    category = models.ForeignKey(Category)
    ... # fields omitted

class Conversation(models.Model):
    sid = models.CharField()
    ... # fields omitted

现在我正在尝试为Category创建一个模型序列化程序,它会返回以下序列化对象:

{
    "name":"blah",
    "conversations":[
        "2af22188c5c97256",    # This is the value of the sid field
        "073aef6aad0883f8",
        "5d3dc73fc8cf34be",
     ]
}

以下是我在序列化程序中的内容:

class CategorySerializer(serializers.ModelSerializer):
    conversations = serializers.SlugRelatedField(many=True,
             read_only=True, 
             source="prediction_set", 
             slug_field='conversation.sid')

    class Meta:
        model = models.Class
        fields = ('class_name', 'conversations')

然而,这不起作用,因为不知何故django不允许我将slug_field设置为对象字段内的字段。有关如何实现这一目标的任何建议吗?

1 个答案:

答案 0 :(得分:1)

您正在使用名为Category的显式表格对ConversationPrediction之间的多对多关系进行建模。 django这样做的方法是明确说明关系两边的多对多,并指定Prediction作为"通过模型":

来自this question的无耻偷走的例子:

class Category(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=255, blank=True,default=None)
    desc = models.TextField(blank=True, null=True )

    ...

class Post(models.Model):
   title = models.CharField(max_length=255)
   pub_date = models.DateTimeField(editable=False,blank=True)
   author = models.ForeignKey(User, null=True, blank=True)
   categories = models.ManyToManyField(Category, blank=True, through='CatToPost')

   ...


class CatToPost(models.Model):
    post = models.ForeignKey(Post)
    category = models.ForeignKey(Category)

    ...

这显示了建立关系的好方法。

同样无耻地从@Amir Masnouri的答案中偷走了:

class CategorySerializer(serializers.ModelSerializer):
      class Meta:
            model = Category
            fields = ('name','slug')

class PostSerializer(serializers.ModelSerializer):

      class Meta:
            model = Post  
            fields = ('id','{anything you want}','categories')
            depth = 2

这显示了一种实现您希望的嵌套序列化行为的好方法。