使用外键将主文件和详细信息保存在DRF中

时间:2018-09-23 21:30:26

标签: django django-rest-framework

我正在尝试从请求中保存实体。

我有两个模型

class Reservation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    userReservation = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    dateStart = models.DateTimeField(null=False, blank=False, default=datetime.now)  

    def __str__(self):
        return str(self.id)


class DetailsReservation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    Reservation = models.ForeignKey(Reservation, blank=False, on_delete=models.CASCADE, null=True, related_name='reservation_details')
    product = models.ForeignKey(Product, blank=False, on_delete=models.CASCADE, null=True, related_name='products_reservation')
    Quantity = models.IntegerField(null=False, blank=False, default=0)

    def __str__(self):
        return self.product.product_Description +" by: " + self.userbyReserva.email

    def save(self, *args, **kwargs):
        self.userbyReserva = self.Reservation.userReservation
        super(DetailsReservation, self).save(args, kwargs)

然后我有两个序列化器

class DetailsReservationSerializer(serializers.ModelSerializer):
    class Meta:
        model = DetailsReservation
        fields = '__all__'


class ReservationSerializer(serializers.ModelSerializer):
    reservation_details = DetailsReservationSerializer(many=True)
    class Meta:
        model = Reservation
        fields = '__all__'

然后在我看来,我有

class makereservation(generics.ListCreateAPIView):

    def post(self, request, *args, **kwargs):
        data = request.data
        data["userReservation"] = request. user.id
        serializer = ReservationSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(status=status.HTTP_201_CREATED)
    return Response(status=status.HTTP_400_BAD_REQUEST)

我正在尝试邮递员(用于模拟请求类型的帖子)

这是我的json

{
    "dateStart": "2020-09-20T13:00:00-05:00",
    "reservation_details": [{
            "product": 1,
            "Quantity": 2
        },
        {
            "productId": 2,
            "Quantity": 2
        }, {
            "productId": 3,
            "Quantity": 1
        }
    ]
}

但是我不知道如何保存它。

  • 首先,我尝试保存保留,在获得这些保留后,并使用id尝试插入DetailsReservation,但不起作用

1 个答案:

答案 0 :(得分:1)

Django Rest Framework不具有创建嵌套对象的内置支持。但是,他们确实提供了一些文档,用于在此处添加此功能:http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects

在创建DetailsReservation对象之后,您必须在ReservationSerializer的create方法中为Reservation添加创建功能。

这是一个可能看起来像的例子:

class ReservationSerializer(serializers.ModelSerializer):
    reservation_details = DetailsReservationSerializer(many=True)
    class Meta:
        model = Reservation
        fields = '__all__'

    def create(self, validated_data):
        details_data = validated_data.pop('reservation_details') #grab the data on details
        reservation = Reservation.objects.create(**validated_data) # create the master reservation object
        for reservation_detail in details_data:
            # create a details_reservation referencing the master reservation
            DetailsReservation.objects.create(**reservation_detail, reservation=reservation)
        return reservation

还有一个小注释,我建议将Reservation中的QuantityDetailsReservation重命名为小写,因为它们是指实例而不是类。更改完成后,我的代码即可工作,但是,将reservation=reservation调用中的DetailsReservation.objects.create更改为Reservation=reservation将使代码在您的当前状态下正常工作。