Невозможно назначить OrderedDict ... должен быть экземпляром Address - PullRequest
0 голосов
/ 22 марта 2020

Попытка иметь сериализатор для сохранения адреса dict, но получить следующее сообщение об ошибке:

Невозможно назначить \ "OrderedDict ([('state', 'ON'), ('location', {'lat': '43 .644905 ',' long ':' -79.399437 '}), (' street1 ',' 580 King St. W. '), (' street2 ',' '), (' city ',' Торонто '), (' почтовый индекс ',' M5V 1M3 '), (' страна ',' США ')]) \ ": \" Venue.address \ "должен быть экземпляром \" Address \ ".

Вот мои сериализаторы:

class AddressSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(required=False)
    state = serializers.CharField(allow_blank=True)
    location = serializers.JSONField(required=False)

    class Meta:
        model = Address
        fields = "__all__"


class VenueSerializer(serializers.ModelSerializer):
    address = AddressSerializer(many=False)
    image = serializers.JSONField(source="images", required=False)

    class Meta:
        model = Venue
        fields = ["id", "hostedbyid", "slug", "name", "image", "address"]
        extra_kwargs = {"id": {"validators": []}}

    def create(self, validated_data):
        address_data = validated_data.pop("address")
        try:
            validated_data["address"] = Address.objects.get(street1=address_data.get("street1"))
        except Address.DoesNotExist:
            validated_data["address"] = Address.objects.create(**address_data)

        try:
            venue = Venue.objects.get(pk=validated_data.get("id"))
        except Venue.DoesNotExist:
            venue = Venue.objects.create(**validated_data)

        return venue

Модели здесь:

class Address(models.Model):
    id = models.IntegerField(primary_key=True)
    street1 = models.TextField()
    street2 = models.TextField(blank=True, null=True)
    city = models.TextField()
    state = models.TextField()
    postalcode = models.TextField()
    country = models.TextField()
    location = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'address'

class Venue(models.Model):
    id = models.IntegerField(primary_key=True)
    hostedbyid = models.IntegerField(blank=True, null=True)
    slug = models.TextField()
    name = models.TextField(blank=True, null=True)
    images = JSONField()
    address = models.ForeignKey(Address, models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'venue'

А вот пример данных, которые я хочу сохранить в своей базе данных:

{
   "venue":{
      "id":2506,
      "hostedbyid":0,
      "slug":"Circus-Afterhours",
      "name":"Circus Afterhours",
      "address":{
         "street1":"917 Rue Sainte-Catherine Est",
         "street2":"",
         "city":"Montreal",
         "state":"QC",
         "postalcode":"H2L 3N5",
         "country":"CA",
         "location":{
            "lat":"45.516609",
            "long":"-73.557777"
         }
      }
   }
}

1 Ответ

0 голосов
/ 23 марта 2020

Полная трассировка стека, надеюсь, это поможет:

HTTP GET https://api.stubsites.com/api/v1/electrostub/events?page=1
wsgiserver_1      |   File "/usr/local/lib/python3.8/threading.py", line 890, in _bootstrap
wsgiserver_1      |     self._bootstrap_inner()
wsgiserver_1      |   File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner
wsgiserver_1      |     self.run()
wsgiserver_1      |   File "/usr/local/lib/python3.8/threading.py", line 870, in run
wsgiserver_1      |     self._target(*self._args, **self._kwargs)
wsgiserver_1      |   File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 80, in _worker
wsgiserver_1      |     work_item.run()
wsgiserver_1      |   File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
wsgiserver_1      |     result = self.fn(*self.args, **self.kwargs)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 277, in thread_handler
wsgiserver_1      |     return func(*args, **kwargs)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/channels/http.py", line 244, in handle
wsgiserver_1      |     response = self.get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 75, in get_response
wsgiserver_1      |     response = self._middleware_chain(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
wsgiserver_1      |     response = get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/utils/deprecation.py", line 94, in __call__
wsgiserver_1      |     response = response or self.get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
wsgiserver_1      |     response = get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/utils/deprecation.py", line 94, in __call__
wsgiserver_1      |     response = response or self.get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
wsgiserver_1      |     response = get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/utils/deprecation.py", line 94, in __call__
wsgiserver_1      |     response = response or self.get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
wsgiserver_1      |     response = get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/utils/deprecation.py", line 94, in __call__
wsgiserver_1      |     response = response or self.get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
wsgiserver_1      |     response = get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/utils/deprecation.py", line 94, in __call__
wsgiserver_1      |     response = response or self.get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
wsgiserver_1      |     response = get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/utils/deprecation.py", line 94, in __call__
wsgiserver_1      |     response = response or self.get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
wsgiserver_1      |     response = get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/utils/deprecation.py", line 94, in __call__
wsgiserver_1      |     response = response or self.get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
wsgiserver_1      |     response = get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/utils/deprecation.py", line 94, in __call__
wsgiserver_1      |     response = response or self.get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
wsgiserver_1      |     response = get_response(request)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
wsgiserver_1      |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
wsgiserver_1      |     return view_func(*args, **kwargs)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/rest_framework/viewsets.py", line 114, in view
wsgiserver_1      |     return self.dispatch(request, *args, **kwargs)
wsgiserver_1      |   File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
wsgiserver_1      |     response = handler(request, *args, **kwargs)
wsgiserver_1      |   File "/src/backend/server/apps/databases/views.py", line 51, in synchronize
wsgiserver_1      |     self.register_synchronize_task(request.data["provider"])
wsgiserver_1      |   File "/src/backend/server/apps/databases/views.py", line 166, in register_synchronize_task
wsgiserver_1      |     provider.get_events()
wsgiserver_1      |   File "/src/backend/server/apps/databases/providers/ElectrostubProvider.py", line 37, in get_events
wsgiserver_1      |     traceback.print_stack()
...