我有两个模型User和Vendor(它们与oneToOne链接,我想创建一个包含新User的Vendor。
问题,当我在我的VendorSerializer的重写方法create()中使用方法User.objects.create(UserSerializer(),validated_data = user_data)时,我得到一个“ create()接受1个位置参数,但给出了2个”错误
除了覆盖UserSerializer()中的create之外,我还能做些什么?已经尝试过
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (
'first_name',
'last_name',
'email',
'username'
)
class VendorSerializer(serializers.ModelSerializer):
user = UserSerializer(required=True)
class Meta:
model = Vendor
fields = ('user','no_rue','adresse','code_postal','ville','pays')
def create(self, validated_data):
user_data = validated_data.pop('user')
user = User.objects.create(UserSerializer(),validated_data=user_data)
vendor, created = Vendor.objects.update_or_create(user=validated_data.pop('user'),no_rue=validated_data.pop('no_rue'),
adresse = validated_data.pop('adresse'),
code_postal = validated_data.pop('code_postal'),
ville = validated_data.pop('ville'),
pays = validated_data.pop('pays'))
return vendor
class Vendor(models.Model):
rating = models.FloatField(
null=True,
blank=True,
validators=[MaxValueValidator(5),MinValueValidator(1)]
)
IBAN = IBANField(null=True,unique=True, default=None)
user = models.OneToOneField(User, on_delete=models.CASCADE)
photo = models.ImageField(blank=True,null=True, upload_to='images') #Param: upload_to='directory'
no_rue = models.PositiveIntegerField()
adresse = models.CharField(max_length = 25)
code_postal = models.PositiveIntegerField(validators=[MaxValueValidator(99999),MinValueValidator(1000)])
ville = modelenter code heres.CharField(max_length = 25)
pays = models.CharField(max_length = 25)
def __str__(self):
if(self.user.first_name == ""):
return self.user.username
else:
return self.user.first_name