Django Rest Framework POST和PUT外键模型

时间:2018-10-19 12:08:01

标签: python django http django-rest-framework

我对模型序列化器有问题。 我的模特

class ItemState(models.Model):
"""Status for a item"""
name = models.CharField(max_length=255, null=True, blank=True)

class Item(models.Model):
    title = models.CharField(max_length=255)
    status = models.ForeignKey(ItemState, on_delete=models.CASCADE)

我的序列化器:

class ItemStateSerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemState
        fields = '__all__'


class ItemSerializer(serializers.ModelSerializer):
    status = ItemStateSerializer(read_only=True)
    class Meta:
        model = Item
        fields = '__all__'

还有我的观点

class ItemViewSet(viewsets.ModelViewSet):
    """ Item view set """
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    permission_classes = (IsOwnerOrAdmin, )

我的问题是,如何在不创建状态对象的情况下进行放置或发布? 我想替换这个

HTTP PUT 
{
   "title": "example",
   "status": {
       "id": 1,
       "name": "hello"
   }
}

以此

HTTP PUT 
{
   "title": "example",
   "status": 1
}

感谢社区!

2 个答案:

答案 0 :(得分:0)

您想保留其他班级还是可以一起摆脱所有课程?似乎更简单:

class Item(models.Model):
    title = models.CharField(max_length=255)
    status = models.CharField(max_length=255)  # or you can change to int if you want

答案 1 :(得分:0)

您可以将两个序列化器字段用于同一模型字段-一个用于详细信息,另一个默认使用id(see this answer)。因此,在您的情况下,您的序列化器可以定义为:

    [HttpPost]
    public IActionResult Create(ContactEntityModels model)
    {

        newContact.firstname = model.firstname;

        var contact = new Entity("contact");
        {
            contact["firstname"] = newContact.firstname;
            contact["parentcustomerid_account"] = newContact.ParentAccount;
        }

        _crmContext.ServiceContext.AddObject(contact);

        _crmContext.ServiceContext.SaveChanges();

        return RedirectToAction("Contacts", "Admin");
    }

现在,您的PUT请求将如您所愿:

class ItemSerializer(serializers.ModelSerializer):
    status_detail = ItemStateSerializer(source='status', read_only=True)

    class Meta:
        model = Item
        fields = '__all__'

但是当您获取HTTP PUT { "title": "example", "status": 1 } 时,它将在Item字段中包含ItemState的详细信息:

status_detail
相关问题