在Django DRF中,我总是在序列化器的更新方法中收到ValueError

时间:2019-02-13 23:44:53

标签: python django django-models django-views django-serializer

我正在使用Django DRF,并且已经在序列化程序中成功创建了create方法,但是不知何故,update方法不希望按我的方式工作。 我总是得到相同的ValueError。

我的模型:

class User(models.Model):
gender = models.CharField(max_length=10, choices=GENDER, default='Male')
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, null=True)
email = models.EmailField(max_length=50)
phone = models.CharField(max_length=15)
password = models.CharField(max_length=100, null=True)


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)


class PartnerCompany(models.Model):
partner = models.ForeignKey(Company, on_delete=models.PROTECT)
contact_person = models.ForeignKey(User, on_delete=models.CASCADE)

我的序列化器

class PartnerCompanySerializer(serializers.ModelSerializer):
partner = CompanySerializer(many=False)
contact_person = ClientUserSerializer(many=False)

class Meta:
    model = PartnerCompany
    fields = '__all__'

def create(self, validated_data):
    partner = validated_data.pop('partner')
    contact_person = validated_data.pop('contact_person')
    partner_instance = Company.objects.create(**partner)
    contact_person_instance = User.objects.create(**contact_person)
    return PartnerCompany.objects.create(partner=partner_instance,
                                         contact_person=contact_person_instance,
                                         **validated_data)


def update(self, instance, validated_data):
    instance.partner = validated_data.get('partner', instance.partner)
    instance.contact_person = validated_data.get('contact_person', instance.contact_person)
    partner_instance = Company.objects.update(**instance.partner)
    instance.save(partner_instance)
    return instance

我的观点:

class PartnerCompanyUpdateByID(generics.RetrieveUpdateAPIView):
lookup_field = 'id'
queryset = PartnerCompany.objects.all()
serializer_class = PartnerCompanySerializer

我总是收到此ValueError:

  在/ partner / update / id / 6处的

ValueError   无法分配“ OrderedDict([('company_name','UBS Switzerland'),('address','Mainstreet 1'),('zip',4102),('city','Basel'),('email' ,'ubs@ubs.ch')])“)”:“ PartnerCompany.partner”必须是“公司”实例。

1 个答案:

答案 0 :(得分:0)

您不应发送 partner_instance 作为instance.save()中的参数。 实例合作伙伴中已经具有新值。

def update(self, instance, validated_data):
    instance.partner = validated_data.get('partner', instance.partner)
    instance.contact_person = validated_data.get('contact_person', instance.contact_person)
    partner_instance = Company.objects.update(**instance.partner)
    instance.partner = partner_instance
    instance.save()
    return instance