我正在使用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' ,'[email protected]')])“):“ PartnerCompany.partner”必须是“ Company”实例。

最佳答案

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

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

关于python - 在Django DRF中,我总是在序列化程序的更新方法中收到ValueError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54681165/

10-12 20:15