django rest框架发布对象关系无法创建

时间:2014-10-18 16:56:17

标签: python django rest django-rest-framework

我无法使Django rest框架创建具有依赖关系的对象。简而言之,这是简化的配置,适用于其他部分更新,删除和创建Employee。但是在使用ForeignKey创建Case到Employee时失败了。

models.py

class Employee(models.Model):
    firstName = models.CharField(max_length=50)
    lastName = models.CharField(max_length=50)

class Case(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Employee, related_name='cases_created')

serializers.py

class SCase (serializers.HyperlinkedModelSerializer):
    author = SEmployeeList(required = True)
    class Meta:
        model = models.Case
        fields = ('url', 'title', 'author', 'id')   
class SEmployee(serializers.HyperlinkedModelSerializer):
        cases_created = SCaseList(many=True, required=False)
        class Meta:
            model = models.Employee
            fields = ('url', 'firstName', 'lastName','cases_created', 'id')

views.py

class EmployeeViewSet(viewsets.ModelViewSet):
    queryset = models.Employee.objects.all()
    serializer_class = serializers.SEmployee

class CaseViewSet(viewsets.ModelViewSet):
    queryset = models.Case.objects.all()
    serializer_class = serializers.SCase

问题是当我创建对象案例时,必须引用作者。

  1. 传递现有对象会创建案例和新员工
  2. POST

    {"author":{"url":"http://localhost:8000/restbase/employee/23/",
               "firstName":"Mark",
               "lastName":"Hilton",
               "cases_created":[],
               "id":23},
     "title":"New Case"
    }
    
    1. 仅传递现有作者的URL失败,因为创建作者失败。
    2. POST

      {"author":"http://127.0.0.1:8000/restbase/employee/23/","title":"New Case"}
      

      RESPONSE

      {"author": [{"non_field_errors": ["Invalid data"]}]}
      
      1. 仅将网址作为作者字段传递,会带来以下转发
      2. POST

        {"author":{"url":"http://127.0.0.1:8000/restbase/employee/23/"},"title":"New Case"}
        

        RESPONSE

        {"author": [{"lastName": ["This field is required."], "firstName": ["This field is required."]}]}
        

1 个答案:

答案 0 :(得分:0)

调查结束后,有一个有效的解决方案。作者无法序列化。

class SCase (serializers.HyperlinkedModelSerializer):
    # removed line: author = SEmployeeList(required = True)
    class Meta:
        model = models.Case
        fields = ('url', 'title', 'author', 'id')   

我仍然不知道如何使用详细信息并创建依赖元素