DRF Django Rest Frameworkを使用して2つのモデルのエントリを作成し、 。私はそれをどのように達成するのですか?Django Rest API、2つのモデルエントリのポストAPIを作成する方法、モデルに外部キーが関連付けられている
私は2つのモデル 持っている - ユーザと従業員モデルOneToOneの関連付けをし、ForeignKeyの会社 た - 会社のモデル
私は従業員モデルのエントリとも会社のモデルエントリを作成し、関連付けるためのポストを持つようにしたいです従業員を会社に派遣します。また、従業員はユーザーデータ(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")