如何通过在PrimarykeyRelated Field中发布完整对象来保存django休息中的关系

时间:2020-12-14 16:09:55

Suppose i have this model

假设我有这个模型

class Track(models.Model):
    user = models.ForeignKey(User)
    order = models.IntegerField()
    title = models.CharField(max_length=100)

Now in my class TrackSerializer if i use this

现在我的班级TrackSerializer如果我使用它

user = serializers.PrimaryKeyRelatedField(required=False)

then i can post the track = {user: 1} and it correctly saves it

然后我可以发布track = {user:1}并正确保存它

Now my problem is in my json i always have complete object like complete user object like

现在我的问题是在我的json中我总是有像完整的用户对象那样的完整对象

track = {user: {id: 1, name: 'test'}}

track = {user:{id:1,name:'test'}}

then i get error that expect pk and got dict

然后我得到错误,期望PK和得到字典

Is there any way that i can post complete object and system automatically takes pk from it.

有什么方法可以发布完整的对象和系统自动从中获取pk。

The problem is i don't want to declare complete serializers separately for all models . eg

问题是我不想为所有模型单独声明完整的序列化器。例如

update_by is usually User object and Django rest automatically takes it as primary key related field. There if want to use complete User object then i have decalre it explicitly as UserSerializer

update_by通常是User对象,Django rest会自动将其作为主键相关字段。如果想要使用完整的User对象,那么我将它明确地decalre为UserSerializer

1 个解决方案

#1


You need to look into nested serializers.

您需要查看嵌套的序列化程序。

#1


You need to look into nested serializers.

您需要查看嵌套的序列化程序。