Django Rest API,如何为2个模型条目创建post api,并具有与模型关联的外键

时间:2017-11-14 08:45:46

标签: django rest api serialization model

我正在尝试使用DRF Django Rest Framework来创建一个后API,为2个模型创建条目并关联外键关系。我该如何做到这一点?

我有2个型号 - OneToOne与User关联的Employee模型,并拥有ForeignKey Company - 公司模式

我希望有一个帖子来创建员工模型条目以及公司模型条目,并将员工与公司关联。员工还要输入用户数据(username,first_name,last_name等)。

以下是代码摘录:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)


class Company(models.Model):
    name = models.CharField(max_length=50)
    tel = models.CharField(max_length=15, blank=True)

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py

class EmployeeWithCompanyCreateView(generics.ListCreateAPIView):
    """This class defines the create behavior of our rest api."""
    queryset = Employee.objects.all()
    serializer_class = EmployeeWithCompanyCreateSerializer

    def perform_create(self, serializer):
        """Save the post data when creating a new bucketlist."""
        serializer.save()

https://gitlab.com/firdausmah/railercom/blob/master/railercom/urls.py

urlpatterns = [
    url(r'^employee/$', EmployeeWithCompanyCreateView.as_view(), name="create"),

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/serializers.py

class EmployeeWithCompanyCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = Employee
        fields = ("id","identity_number", "tel")

1 个答案:

答案 0 :(得分:0)

您当前的解决方案有些问题:EmployeeWithCompanyCreateSerializer类的字段列表与Employee类的字段不匹配。 在你的问题背景下,我建议你手工编写复杂的视图。