Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Django Rest框架中保存实例嵌套序列化程序_Python_Django_Serialization_Django Rest Framework - Fatal编程技术网

Python 在Django Rest框架中保存实例嵌套序列化程序

Python 在Django Rest框架中保存实例嵌套序列化程序,python,django,serialization,django-rest-framework,Python,Django,Serialization,Django Rest Framework,我在Django Rest框架中的嵌套序列化程序中保存实例Live_时遇到问题。希望你们能帮助我!我认为这只是一个基本问题 我的序列化程序: 我认为在编写保存实例时会出现错误 class CityLiveInSerializer(ModelSerializer): country = CharField(required=False, source='country.name') class Meta: model = City fields =

我在Django Rest框架中的嵌套序列化程序中保存实例Live_时遇到问题。希望你们能帮助我!我认为这只是一个基本问题

我的序列化程序:

我认为在编写保存实例时会出现错误

class CityLiveInSerializer(ModelSerializer):
    country = CharField(required=False, source='country.name')
    class Meta:
        model = City
        fields = [
            'name',
            'slug',
            'country'
        ]    

class UserEditSerializer(ModelSerializer):
    live_in = CityLiveInSerializer(source='profile.live_in')
    about = serializers.CharField(source='profile.about')
    class Meta:
        model = User
        fields = [
            'username',
            'live_in',
            'about',
        ]

    def update(self, instance, validated_data):
        instance.username = validated_data.get('username', instance.username)
        instance.save()
        # Update Serializers Profile
        if (validated_data.get('profile') is not None):
            profile_data = validated_data.pop('profile')
            profile = instance.profile
            profile.about = profile_data.get('about', profile.about)
            profile.save()

        if (validated_data.get('live_in') is not None):
          live_in_data = validated_data.pop('live_in')
          try:
              city = City.objects.get(name=live_in_data['name'])
          except City.DoesNotExist:   
              city = City.objects.create(**live_in_data)
          instance.profile.live_in = city
          instance.profile.save()
        return instance
我的城市模型(入住)

我的个人资料模型

class Profile(models.Model):
    # Extend User
    user = models.OneToOneField(User, unique=True)
    about = models.TextField(max_length=1000, default='', blank=True, null=True)
    live_in = models.ForeignKey(City, null=True, blank=True, related_name="live_in")
邮递员发送的数据(Json)

跟踪错误:

数据中的文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site packages/rest\u framework/serializers.py” 263self.\u data=self.to\u表示(self.instance)

to_表示形式中的文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site packages/rest_framework/serializers.py” 488属性=字段。获取属性(实例)

get_属性中的文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site packages/rest_framework/fields.py” 463提升类型(exc)(msg)

异常类型:AttributeError at/api/v1/users/account/edit/ 异常值:在序列化程序
UserEditSerializer
上尝试获取字段
live\u的值时,获取了AttributeError。
序列化程序字段的名称可能不正确,并且与
用户
实例上的任何属性或键都不匹配。
最初的异常文本是:“User”对象没有属性“live_in”。

首先,在这种情况下,您不需要
many=True
。相关对象列表需要它,但您只能通过一个城市。 其次,
live\u in
是配置文件模型的属性,所以您需要更新配置文件并添加源参数:

live_in = CityLiveInSerializer(source="profile.live_in")

def update(self, instance, validated_data):
    instance.username = validated_data.get('username', instance.username)
    instance.save()
    # Update Serializers Profile
    if (validated_data.get('profile') is not None):
        profile_data = validated_data.pop('profile')
        profile = instance.profile
        profile.about = profile_data.get('about', profile.about)
        if (profile_data.get('live_in') is not None):
            live_in_data = profile_data.pop('live_in')
            try:
                city = City.objects.get(name=live_in_data["name"])
            except City.DoesNotExist:   
                city = City.objects.create(**live_in_data)
        profile.live_in = city 
        profile.save()

    return instance
在这种情况下,需要允许创建不带国家/地区的城市,因此需要将null=True、blank=True添加到国家/地区属性:

class BaseCity(Place, SlugModel):
    name = models.CharField(max_length=200, db_index=True, verbose_name="standard name")
    country = models.ForeignKey(swapper.get_model_name('cities', 'Country'),
                            related_name='cities', null=True, blank=True)

首先,在这种情况下,您不需要
many=True
。相关对象列表需要它,但您只能通过一个城市。 其次,
live\u in
是配置文件模型的属性,所以您需要更新配置文件并添加源参数:

live_in = CityLiveInSerializer(source="profile.live_in")

def update(self, instance, validated_data):
    instance.username = validated_data.get('username', instance.username)
    instance.save()
    # Update Serializers Profile
    if (validated_data.get('profile') is not None):
        profile_data = validated_data.pop('profile')
        profile = instance.profile
        profile.about = profile_data.get('about', profile.about)
        if (profile_data.get('live_in') is not None):
            live_in_data = profile_data.pop('live_in')
            try:
                city = City.objects.get(name=live_in_data["name"])
            except City.DoesNotExist:   
                city = City.objects.create(**live_in_data)
        profile.live_in = city 
        profile.save()

    return instance
在这种情况下,需要允许创建不带国家/地区的城市,因此需要将null=True、blank=True添加到国家/地区属性:

class BaseCity(Place, SlugModel):
    name = models.CharField(max_length=200, db_index=True, verbose_name="standard name")
    country = models.ForeignKey(swapper.get_model_name('cities', 'Country'),
                            related_name='cities', null=True, blank=True)

你能添加用户和配置文件模型吗?又是你^^。添加您可以添加用户和配置文件模型吗?又是您^^。为Country添加了
null=True,blank=True
将修复该问题,但如果我希望数据响应包含国家数据,该如何处理?@FeedGit在这种情况下,您需要为您的数据再添加一个级别:
{“live_in”:{“name”:“Canamp”,“Country”:{“name”:“CountryName”}
。这意味着您需要创建另一个序列化程序CountrySerializer并将其添加到CityLiveInSerializer。此外,您还需要像在UserEditSerializer中那样覆盖CityLiveInSerializer的创建和更新方法。另外,是的,是我,再次您好:)请使用Traceback查看我上面的新代码!@FeedGit,或者您只能允许用户访问use存在于DB国家/地区。在这种情况下,您不需要嵌套关系。用户只能发送国家/地区id:
{“live_in:{“name:“Encamp”,“country:“1”}
@FeedGit我想应该是
live_in=CityLiveInSerializer(source=“profile.live_in”)
检查更新。
null=True,blank=True
国家/地区将修复此问题,但如果我希望数据响应具有国家/地区数据,该如何处理?@FeedGit在这种情况下,您需要为数据添加一个级别:
{“live_in”:{“name”:“Encamp”,“Country”:{“name”:“CountryName”}
。这意味着您需要创建另一个序列化程序CountrySerializer并将其添加到CityLiveInSerializer。此外,您还需要像在UserEditSerializer中那样覆盖CityLiveInSerializer的创建和更新方法。另外,是的,是我,再次您好:)请使用Traceback查看我上面的新代码!@FeedGit,或者您只能允许用户访问use存在于DB国家/地区。在这种情况下,您不需要嵌套关系。用户只能发送国家/地区id:
{“live_in:{“name:“Encamp”,“country:“1”}
@FeedGit我想应该是
live_in=CityLiveInSerializer(source=“profile.live_in”)
检查更新。