我前面有从串行器中获取的数据,除了丢失了两个数据“用户”和“场所”。
const workplaceBody = {
"user": this.currentUser.id,
"establishment": response.body.id,
"is_main_establishment": false
};
当我在序列化程序中打印validated_data时,我只有一个“ is_main_ Establishment”数据。
{'is_main_establishment': False}
我想创建一个与企业关联的工作场所。
this.workplaceEstablishment.create(workplaceBody).subscribe(response => {
console.log(response);
});
我的工作场所序列化器:
class WorkplacesSerializer(ModelSerializer):
id = IntegerField(source="establishment.id", read_only=True)
name = CharField(source="establishment.name", read_only=True)
type = CharField(source="establishment.type", read_only=True)
selected = SerializerMethodField()
def get_selected(self, instance):
#print(instance)
#print(self.context["request"].data)
return (
get_selected_establishment_id_from_request(self.context["request"])
#"== instance.id
)
def create(self, validated_data):
print(validated_data)
workplace = UserWorksAtEstablishment.objects.create(
**validated_data, establishment_id=validated_data.establishment, user_id=validated_data.user
)
return workplace
class Meta:
model = UserWorksAtEstablishment
fields = ("id", "name", "type", "is_main_establishment", "selected")
我不明白为什么我会丢失这些数据。
提前谢谢
答案 0 :(得分:0)
确保user
和establishment
是表的模型中的字段,然后可以通过执行以下操作将它们添加到序列化器中:
class Meta:
model = UserWorksAtEstablishment
fields = ("id", "user", "establishment", "name", "type", "is_main_establishment", "selected")
或仅添加所有字段:
class Meta:
model = UserWorksAtEstablishment
fields = '__all__'