Django 2.1 create方法创建嵌套字段(foreignkey关系)。使用Django的Rest框架

时间:2019-02-13 14:15:55

标签: django django-models django-rest-framework django-serializer

我应该在jango 2.1中使用哪种方法来创建方法,以添加也支持嵌套字段(ForeignKey关系)创建的新对象。我总是收到错误消息:

  

/ client / create /中的AssertionError   .create()方法默认情况下不支持可写的嵌套字段。

用户模型

class User(models.Model):
gender = models.CharField(max_length=10, choices=GENDER)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
position = models.CharField(max_length=50)
birthday = models.DateField(auto_created=False)
email = models.EmailField(max_length=50)
phone = models.CharField(max_length=15)
password = models.CharField(max_length=100)

def __str__(self):
    return f"{self.first_name} {self.last_name} {self.position} {self.email} {self.phone} {self.password}"

公司型号

class Company(models.Model):
company_name = models.CharField(max_length=50, blank=False)
address = models.CharField(max_length=50, blank=False)
zip = models.IntegerField(blank=False)
city = models.CharField(max_length=50, blank=False)
email = models.EmailField(max_length=50, blank=False)

def __str__(self):
    return f"{self.company_name} {self.address} {self.zip} {self.city}"

客户公司

class ClientCompany(models.Model):
client = models.ForeignKey(Company, on_delete=models.PROTECT)
contact_person = models.ForeignKey(User, on_delete=models.PROTECT)
status = models.CharField(max_length=15, choices=STATUS, default='Aktiv')

def __str__(self):
    return f"{self.client} {self.contact_person} {self.status}"

用户序列化器

class UserSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields = '__all__'

ClientCompanySerializer

class ClientCompanySerializer(serializers.ModelSerializer):
    client = CompanySerializer(many=False, read_only=False)
    contact_person = ClientUserSerializer(many=False, read_only=True)

    class Meta:
        model = ClientCompany
        fields = '__all__'

UserUrls

    urlpatterns = [
path('update/id<int:id>', UpdateUserByID.as_view(), name='user-update'),
path('id/<int:id>', GetUserByID.as_view(), name='user-id'),
path('create', CreateUser.as_view(), name='create-user'),
path('delete/id/<int:id>', DeleteUserByID.as_view(), name='delete-user'),

]

CompanyUrls

urlpatterns = [
path('update/id<int:id>', CompanyUpdateByID.as_view(), name='company-udpate'),
path('id/<int:id>', CompanyById.as_view(), name='company-id'),
path('create/', CreateCompany.as_view(), name='company-create'),
path('delete/id/<int:id>', DeleteCompanyByID.as_view(), name='company-delete')

]

CompanyView

class CreateCompany(generics.CreateAPIView):
queryset = Company.objects.all()
serializer_class = CompanySerializer

我的目标是在/ company / create /

网址中创建一个新公司(以及相关的fk'contact_person')

是否可以在“ ClientCompanySerializer”中创建相关的“ contact_person”,还是应该使用其他方法?

1 个答案:

答案 0 :(得分:0)

您需要在如下序列化程序中覆盖默认的createupdate方法:

首先从read_only=True删除contact_person

def create(self, validated_data):
client = validated_data.pop('client')
contact_person = validated_data.pop('contact_person')
client_instance = Company.object.create(**client)
contact_person_instance = User.object.create(**contact_person)
return ClientCompany.objects.create(client=client_instance,contact_person=contact_person_instance , **validated_data)

还为update实现类似的方法