Django остальные рамки, получил AttributeError, когда создать много ко многим - PullRequest
0 голосов
/ 25 апреля 2018

Я пытаюсь добавить заказ с продуктом, переопределив метод .create ():

class OrderCreateSerializer(ModelSerializer):
    product = PrimaryKeyRelatedField(queryset=Product.objects.all())

    class Meta:
        model = Order
        fields = [
            'owner',
            'product'
        ]

    def create(self, validated_data):
        product = validated_data.pop('product')
        order = Order.objects.create(**validated_data)
        order.product_set.add(product)
        return order

Но получил эту ошибку:

Получена ошибка AttributeError при попытке получить значение для поля product на сериализаторе OrderCreateSerializer. Поле сериализатора может иметь неправильное имя и не соответствовать ни одному атрибуту или ключу в экземпляре Order. Исходный текст исключения был: у объекта 'Order' нет атрибута 'product'.

Traceback

Traceback (most recent call last):
    File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, 
**callback_kwargs)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/rest_framework/generics.py", line 192, in post
    return self.create(request, *args, **kwargs)
  File "/home/denis/Projects/lunch_order/apps/api/views.py", line 24, 
in create
    headers = self.get_success_headers(serializer.data)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/rest_framework/serializers.py", line 560, in data
    ret = super(Serializer, self).data
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/rest_framework/serializers.py", line 262, in data
    self._data = self.to_representation(self.instance)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/rest_framework/serializers.py", line 514, in 
to_representation
    attribute = field.get_attribute(instance)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/rest_framework/relations.py", line 177, in get_attribute
    return super(RelatedField, self).get_attribute(instance)
  File "/home/denis/Projects/lunch_order/.venv/lib/python3.5/site- 
packages/rest_framework/fields.py", line 462, in get_attribute
     raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for 
field `product` on serializer `OrderCreateSerializer`.
The serializer field might be named incorrectly and not match any 
attribute or key on the `Order` instance.
Original exception text was: 'Order' object has no attribute 
'product'.

Но заказ и продукт созданы

Просмотры :

class OrderCreateAPIView(CreateAPIView):
    model = Order
    serializer_class = OrderCreateSerializer

Модель

class Order(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)

class Product(models.Model):
    order = models.ManyToManyField(Order, blank=True)
    title = models.CharField(max_length=120)
    manufacturer = models.CharField(max_length=120)
    price = models.IntegerField()  

EDIT Получил эту ошибку после изменения кода:

TypeError: 
<django.db.models.fields.related_descriptors.
create_forward_many_to_many_manager.<locals>.ManyRelatedManager object 
at 0x7fe9981e0b70> is not JSON serializable

1 Ответ

0 голосов
/ 25 апреля 2018

По умолчанию обратное связанное имя для множества полей равно model_set, поэтому используйте source=product_set аргумент для поля продукта.Также, поскольку product_set содержит много объектов, используйте many=True для этого поля:

class OrderCreateSerializer(ModelSerializer):
    product = PrimaryKeyRelatedField(source='product_set', many=True, queryset=Product.objects.all())
...