禁止直接分配到相关集合的反面。改为使用time\u interval.set()

2024-05-16 20:43:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有3种型号:订单、订单时间定位和时间间隔。订单与orderTimelocation之间存在一对多关系,与时间间隔之间存在一对多关系:

class Order(models.Model):
    customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer')
    retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer')
    date_publish = models.DateField()
    date_available = models.DateField()
    weight = models.DecimalField(decimal_places=2, max_digits=5)
    
class orderTimelocation(models.Model):
    longitude = models.DecimalField(decimal_places=8, max_digits=12)
    latitude = models.DecimalField(decimal_places=8, max_digits=12)
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='ordertimelocation', null=True)

class timeInterval(models.Model):
    start = models.DateTimeField()
    end = models.DateTimeField()
    order_timelocation = models.ForeignKey(orderTimelocation, related_name='time_interval', on_delete=models.CASCADE)

正如文档所示,我正在使用可写嵌套序列化程序

class OrderSerializer(serializers.ModelSerializer):
    ordertimelocation = orderTimelocationSerializer(many=True)

    class Meta:
        model = Order
        fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation']

    def create(self, validated_data):
        timelocations_data = validated_data.pop('ordertimelocation')
        order = Order.objects.create(**validated_data)
        
        for timelocation_data in timelocations_data:
            orderTimelocation.objects.create(order=order, **timelocation_data)
        return order

class orderTimelocationSerializer(serializers.ModelSerializer):
    time_interval = timeIntervalSerializer(many= True)

    class Meta:
        model = orderTimelocation
        fields = ('longitude', 'latitude', 'time_interval')


    def create(self, validated_data):
        time_intervals_data = validated_data.pop('time_interval')
        ordertimelocation = orderTimelocation.objects.create(**validated_data)
        for time_interval_data in time_intervals_data:
           orderTimelocation.objects.create(ordertimelocation=ordertimelocation, **time_interval_data)
        return ordertimelocation

class timeIntervalSerializer(serializers.ModelSerializer):
    class Meta:
        model = timeInterval
        fields = ['start', 'end']

错误如下:

Traceback (most recent call last):
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/sentry_sdk/integrations/django/views.py", line 67, in sentry_wrapped_callback
    return callback(request, *args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/generics.py", line 190, in post
    return self.create(request, *args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/mixins.py", line 19, in create
    self.perform_create(serializer)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/mixins.py", line 24, in perform_create
    serializer.save()
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/serializers.py", line 205, in save
    self.instance = self.create(validated_data)
  File "/home/miguel/workspace/projeto-final/backend/delivery_api/serializers/order_serializer.py", line 17, in create
    orderTimelocation.objects.create(order=order, **timelocation_data)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/db/models/query.py", line 451, in create
    obj = self.model(**kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/db/models/base.py", line 498, in __init__
    _setattr(self, prop, kwargs[prop])
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 545, in __set__
    raise TypeError(
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use time_interval.set() instead.

我不知道我做错了什么,因为我的代码与文档中的代码相似


Tags: inpyenvbackendhomemodelslibpackages
1条回答
网友
1楼 · 发布于 2024-05-16 20:43:21

这个问题是因为在OrderSerializer.create中,每个timelocation_data都有time_interval。您需要弹出它,然后处理:

class OrderSerializer(serializers.ModelSerializer):
    ordertimelocation = orderTimelocationSerializer(many=True)

    class Meta:
        model = Order
        fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation']

    def create(self, validated_data):
        timelocations_data = validated_data.pop('ordertimelocation')
        order = Order.objects.create(**validated_data)
        
        for timelocation_data in timelocations_data:
            time_intervals_data = validated_data.pop('time_interval') # <  This will fix the error
            ordertimelocation = orderTimelocation.objects.create(order=order, **timelocation_data)
            for time_interval_data in time_intervals_data:
                timeInterval.objects.create(order_timelocation=ordertimelocation, **time_interval_data)

        return order

或者只使用orderTimelocationSerializer表示timelocations_data,让它自己处理:

class OrderSerializer(serializers.ModelSerializer):
    ordertimelocation = orderTimelocationSerializer(many=True)

    class Meta:
        model = Order
        fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation']

    def create(self, validated_data):
        timelocations_data = validated_data.pop('ordertimelocation')
        order = Order.objects.create(**validated_data)
        
        for timelocation_data in timelocations_data:
            order_time_location_serializer = orderTimelocationSerializer(data=timelocation_data)
            order_time_location_serializer.is_valid(raise_exception=True)
            order_time_location = order_time_location_serializer.save()
            order_time_location.order = order
            order_time_location.save()

        return order

相关问题 更多 >