如何使用serializer来创建一个带有外键的新对象 [英] How to use serializer to create a new object with a foreignkey

查看:1293
本文介绍了如何使用serializer来创建一个带有外键的新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这个模型:

class Tweek(models.Model):
    content = models.CharField(max_length=140)
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, related_name='author')

    class Meta:
        ordering = ['-date']

    def __unicode__(self):
        return self.content

一切正常,现在我尝试绑定一个休息的api uppon。我已经安装了django休息框架,我可以检索tweeks,但我不能创建新的。

Everthing works fine, now i try to bind a rest api uppon. I've installed the django rest framework and I can retrieve tweeks but I cannot create new ones.

我有这个序列化器为Tweek模型:

I have this serializer for the Tweek model:

class TweekSerializer(serializers.ModelSerializer):
    author = UserSerializer()

    class Meta:
        model = Tweek
        fields = ('content', 'date', 'author')

    def create(self, validated_data):
        author_data = validated_data.pop('author')
        author = User.objects.get(username=author_data)

        return Tweek.objects.create(author=author, **validated_data)

,用户序列化器通常看起来像:

and the user serializer somply looks like:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name')

但帖子返回

{
    "author": {
        "username": [
            "This field must be unique."
        ]
    }
}

但是我失去了这种情况:(
任何想法?

I've followed the doc, but i'm lost with this case :( Any idea ?

推荐答案

这里的问题是任何字段与 unique = True 设置,用户模型中的用户名字段,rel =nofollow noreferrer自动 UniqueValidator 添加到序列化器字段,这个验证器是什么触发您看到的消息,您可以通过将验证器设置为<$ c来删除验证$ c> [] (一个空列表)初始化该字段。

The issue here is that any field with unique=True set, like the username field on the Django User model, will automatically have the UniqueValidator added to the serializer field. This validator is what is triggering the message you are seeing, and you can remove the validation by setting validators to [] (an empty list) when initializing the field.

你将遇到的另一个问题是你正在尝试创建一个对象使用外键,但是您在回复中返回完整的序列化对象。通过使用第二个字段设置id,即只写,并使用原始的serializer字段进行嵌套表示,并使其成为只读,这个问题更容易解决。

The other issue that you are going to run into is that you are trying to create an object with a foreign key, but you are returning the full serialized object in your response. This issue is easier fixed by using a second field for setting the id, that is write-only, and using the original serializer field for the nested representation and making that read-only.

您可以在以下堆栈溢出问题中找到更多信息: DRF:使用嵌套的序列化程序进行简单的外键分配?

You can find more information in the following Stack Overflow question: DRF: Simple foreign key assignment with nested serializers?

这篇关于如何使用serializer来创建一个带有外键的新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆