gpt4 book ai didi

django - 禁止直接分配给相关集合的背面。改用addresses.set()

转载 作者:行者123 更新时间:2023-12-03 09:31:33 27 4
gpt4 key购买 nike

我将创建和更新嵌套关系,但它没有按预期工作我有三个模型用户、配置文件和地址。 Profile 模型是 Address 模型中的 FK

配置文件/模型.py

class Address(models.Model):
profile = models.ForeignKey(Profile, related_name='addresses', on_delete=models.CASCADE)
country = models.CharField(max_length=255)
city = models.CharField(max_length=255)
state = models.CharField(max_length=100)
zip_code = models.CharField(max_length=50)
address = models.CharField(max_length=1000)

profiels/serializers.py
class ProfileSerializer(serializers.ModelSerializer):
addresses = AddressSerializer(many=True)

class Meta:
model = Profile
fields = ['gender', 'date_of_birth', 'hometown', 'phone', 'addresses']

def create(self, validated_data):
addresses_data = validated_data.pop('addresses')
profile = Profile.objects.create(**validated_data)
for address_data in addresses_data:
Address.objects.create(profile=profile, **address_data)
return profile

用户/序列化器.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
profile = ProfileSerializer(required=True)
class Meta:
model = User
fields = ['id', 'url', 'first_name', 'last_name', 'email', 'password', 'profile']
extra_kwargs = {'password': {'write_only': True}}

def create(self, validated_data):
profile_data = validated_data.pop('profile')
password = validated_data.pop('password')
user = User(**validated_data)
user.set_password(password)
user.save()
Profile.objects.create(user=user, **profile_data)
return user

def update(self, instance, validated_data):
profile_data = validated_data.pop('profile')
profile = instance.profile
instance.email = validated_data.get('email', instance.email)
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.save()

profile.gender = profile_data.get('gender', profile.gender)
profile.date_of_birth = profile_data.get('date_of_birth', profile.date_of_birth)
profile.hometown = profile_data.get('hometown', profile.hometown)
profile.phone = profile_data.get('phone', profile.phone)
profile.addresses = profile_data.get('addresses', profile.addresses)
profile.save()

它与我可以创建和更新的用户和配置文件配合得很好,但是当我添加时 地址 它给了我上面标题中显示的错误。我还不知道如何解决嵌套内部嵌套关系。任何帮助将不胜感激)预先感谢!

最佳答案

您的问题与这条线有关

profile.addresses = profile_data.get('addresses', profile.addresses)

正如错误消息所暗示的那样,不允许直接分配给关系的背面。你想要做的是使用 set() 代替。
profile.addresses.set([list of new addresses])

https://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.set

关于django - 禁止直接分配给相关集合的背面。改用addresses.set(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57406706/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com