如何在序列化程序中创建字段,以避免出现“ TypeError:无法解压缩不可迭代的地址对象”错误?

问题描述 投票:0回答:1

我正在使用Django 2.0,Python 3.7和django-address模块​​-https://github.com/furious-luke/django-address。简而言之,Address对象取决于Locality对象(城市),并且我已经创建了自己的模型,该模型取决于Address对象...

class Coop(models.Model):
    name = models.CharField(max_length=250, null=False)
    type = models.ForeignKey(CoopType, on_delete=None)
    address = AddressField(on_delete=models.CASCADE)
    enabled = models.BooleanField(default=True, null=False)
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)
    web_site = models.TextField()

然后,我创建了以下序列化程序来处理处理要上传的JSON,以创建我的模型及其地址对象...

class AddressTypeField(serializers.PrimaryKeyRelatedField):

    queryset = Address.objects

    def to_internal_value(self, data):
        if type(data) == dict:
            locality = data['locality']
            locality, created = Locality.objects.get_or_create(**locality)
            data['locality'] = locality
            address, created = Address.objects.create(**data)
            # Replace the dict with the ID of the newly obtained object
            data = address.pk
        return super().to_internal_value(data)
...

class CoopSerializer(serializers.ModelSerializer):
    type = CoopTypeField()
    address = AddressTypeField()

    class Meta:
        model = Coop
        fields = ['id', 'name', 'type', 'address', 'enabled', 'phone', 'email', 'web_site']

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['type'] = CoopTypeSerializer(instance.type).data
        rep['address'] = AddressSerializer(instance.address).data
        return rep

    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        return Coop.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `Coop` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.type = validated_data.get('type', instance.type)
        instance.address = validated_data.get('address', instance.address)
        instance.enabled = validated_data.get('enabled', instance.enabled)
        instance.phone = validated_data.get('phone', instance.phone)
        instance.email = validated_data.get('email', instance.email)
        instance.web_site = validated_data.get('web_site', instance.web_site)
        instance.save()
        return instance

但是,当我将以下JSON发布到我的端点时...

{
        "name": "1872",
        "type": {
            "name": "Coworking Space"
        },
        "address": {
            "street_number": "222",
            "route": "1212",
            "raw": "222 W. Merchandise Mart Plaza, Suite 1212",
            "formatted": "222 W. Merchandise Mart Plaza, Suite 1212",
            "latitude": 41.88802611,
            "longitude": -87.63612199,
            "locality": {
                "name": "Chicago",
                "postal_code": "60654",
                "state": 1
            }
        },
        "enabled": true,
        "phone": null,
        "email": null,
        "web_site": "http://www.1871.com/"
}

我收到以下错误...

web_1     | Internal Server Error: /coops/
web_1     | Traceback (most recent call last):
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner
web_1     |     response = get_response(request)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 128, in _get_response
web_1     |     response = self.process_exception_by_middleware(e, request)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
web_1     |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
web_1     |     return view_func(*args, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 69, in view
web_1     |     return self.dispatch(request, *args, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch
web_1     |     response = self.handle_exception(exc)
web_1     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception
web_1     |     self.raise_uncaught_exception(exc)
web_1     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
web_1     |     raise exc
web_1     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch
web_1     |     response = handler(request, *args, **kwargs)
web_1     |   File "/app/maps/views.py", line 20, in post
web_1     |     if serializer.is_valid():
web_1     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 234, in is_valid
web_1     |     self._validated_data = self.run_validation(self.initial_data)
web_1     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 433, in run_validation
web_1     |     value = self.to_internal_value(data)
web_1     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 490, in to_internal_value
web_1     |     validated_value = field.run_validation(primitive_value)
web_1     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/relations.py", line 153, in run_validation
web_1     |     return super().run_validation(data)
web_1     |   File "/usr/local/lib/python3.7/site-packages/rest_framework/fields.py", line 565, in run_validation
web_1     |     value = self.to_internal_value(data)
web_1     |   File "/app/maps/serializers.py", line 27, in to_internal_value
web_1     |     address, created = Address.objects.create(**data)
web_1     | TypeError: cannot unpack non-iterable Address object

如何在序列化程序中正确设置我的地址位置字段,以避免发生此错误?

django python-3.x serialization django-models django-serializer
1个回答
0
投票

错误'cannot unpack non-iterable Address object'来自以下事实:create仅返回地址对象,而不返回元组(创建的地址)。这是文档:https://docs.djangoproject.com/fr/2.2/ref/models/querysets/#django.db.models.query.QuerySet.create

© www.soinside.com 2019 - 2024. All rights reserved.