【发布时间】:2018-04-27 03:09:49
【问题描述】:
我正在尝试使用 DRF Django Rest Framework 创建一个发布 API 来为 2 个模型创建条目并关联外键关系。我该如何做到这一点?
我有 2 个模型 - OneToOne 与 User 关联的 Employee 模型,并有一个 ForeignKey 公司 - 公司模式
我想要一个帖子来创建员工模型条目以及公司模型条目并将员工与公司相关联。我还想输入员工数据(用户名、名字、姓氏等)。
以下是代码摘录:
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")
【问题讨论】:
标签: django rest api serialization model