外键Django中的序列化器

时间:2018-09-17 23:58:23

标签: django django-models django-rest-framework

我需要从Reservation,ReservationDetails和产品中获取信息,但只需获取Reservation和ReservationDetails

我有3个模型

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)
    dateFinish = models.DateTimeField(null=False, blank=False, default=datetime.now)
    date_Created = models.DateTimeField(auto_now_add=True)
    date_Modified = models.DateTimeField(auto_now=True, db_index=True)

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


class DetailsReservation(models.Model):
    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)
    userbyReserva = models.ForeignKey(User, editable=False, on_delete=models.CASCADE, default=1)

class Product(models.Model):
    product_Description = models.CharField(max_length=255)
    Quantity = models.IntegerField(null=False, blank=False, default=0)
    Quantity_Max_Reservation = models.IntegerField(null=False, blank=False, default=0)
    product_Comments = models.CharField(max_length=255)
    size = models.CharField(max_length=10, null=True)
    product_Status = models.BooleanField(default=True)
    category = models.ForeignKey(Category,  on_delete=models.CASCADE, null=True, related_name='products')
    date_Created = models.DateTimeField(default=datetime.now, blank=True)
    date_Modified = models.DateTimeField(default=datetime.now, blank=True)

我试图创建序列化器

class ReservationDetailsSerializers(serializers.ModelSerializer):
    products = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), required=False)
    class Meta:
        model= DetailsReservation
        fields =  ['Reservation', 'Quantity', 'userbyReserva', 'products']


class ReservationDetailsListSerializer(serializers.ModelSerializer):
    reservation_details = ReservationDetailsSerializers(many=True)
    class Meta:
        model = Reservation
        fields = ['id', 'userReservation', 'dateStart', 'dateFinish', 'reservation_details']

但响应未显示此字段

[
    {
        "id": "6d87ba1c-61bc-41bd-80c8-31a51df8d32f",
        "userReservation": 1,
        "dateStart": "2018-09-16T17:19:34-05:00",
        "dateFinish": "2018-09-16T17:19:35-05:00",
        "reservation_details": [
            {
                "Reservation": "6d87ba1c-61bc-41bd-80c8-31a51df8d32f",
                "Quantity": 1,
                "userbyReserva": 1
                >>"here should show this information product"
            }
        ]
    },
    {
        "id": "0ed26395-2579-4c40-9a63-460f5095ac51",
        "userReservation": 2,
        "dateStart": "2018-09-16T19:21:24-05:00",
        "dateFinish": "2018-09-16T19:21:24-05:00",
        "reservation_details": [
            {
                "Reservation": "0ed26395-2579-4c40-9a63-460f5095ac51",
                "Quantity": 1,
                "userbyReserva": 2
            }
        ]
    }
]

这是我的views.py

class getAllReservationDetails(generics.ListCreateAPIView):

    queryset = Reservation.objects.prefetch_related('reservation_details')
    print(queryset.query)
    serializer_class = ReservationDetailsListSerializer
    def get_object(self):
        queryset = self.queryset()
        obj = get_object_or_404(queryset)
        return obj

我查看了此Link,但我不知道,为什么不显示信息产品。

但是,这没有我想要的那样。

我该怎么办?

2 个答案:

答案 0 :(得分:1)

MyClass 模型没有 DetailsReservation 属性,但是具有 products 。< br />
因此,请从 product 中删除“ s ”,或在中使用 products > source = 'product' 序列化程序


方法-1 :删除“ s

ReservationDetailsSerializers



方法-2 :指定 class ReservationDetailsSerializers(serializers.ModelSerializer): product = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), required=False) class Meta: model= DetailsReservation fields = ['Reservation', 'Quantity', 'userbyReserva', 'product'] 参数

source


更新

我认为您需要 嵌套序列化器表示形式 。如果是这样,您必须定义一个单独的序列化程序(例如class ReservationDetailsSerializers(serializers.ModelSerializer): products = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), required=False, source='product') class Meta: model = DetailsReservation fields = ['Reservation', 'Quantity', 'userbyReserva', 'products'])并将其添加到 ProductSerializer 而不是 {{1 }}

ReservationDetailsSerializers

因此方法1 成为

serializers.PrimaryKeyRelatedField()

方法2 成为

#new serializer class
class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__' # you can specify the fields here

答案 1 :(得分:1)

您是否尝试为产品模型创建序列化程序并在ReservationDetailsS​​erializers上使用它?

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

class ReservationDetailsSerializers(serializers.ModelSerializer):
    products = ProductSerializer(source='product', required=False)
    class Meta:
        model= DetailsReservation
        fields =  ['Reservation', 'Quantity', 'userbyReserva', 'products']

您可以在Specifying nested serialization

上找到有关此主题的更多信息