2017-11-14 7 views
0

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") 

答えて

0

あなたの現在のソリューションは、間違ったいくつかのことがあります。EmployeeWithCompanyCreateSerializerクラスのフィールドリストは、Employeeクラスのフィールドの不一致です。 質問の文脈では、複雑なビューを手書きで書くことをお勧めします。

関連する問題