从 Django 的外键表中获取所有字段值的列表

时间:2021-03-22 13:13:52

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

我是 Django 的新手,目前正在尝试外键概念。我有三个模型,如下所示。

class Basket(models.Model):
    basket_name = models.CharField(max_length=5, unique=True)

    def __str__(self):
        return self.basket_name

class Product(models.Model):
    Grams = 'GM'
    Kilograms = 'KG'
    WeightBased = 'WPG'
    QuantityBased = 'CPG'
    PRODUCT_UNIT_WT_CHOICES=[
        (Grams, 'Grams'),
        (Kilograms, 'Kilograms')
    ]
    PRODUCT_TYPE_CHOICES =[
        (WeightBased, 'Weight Based Product'),
        (QuantityBased, 'Quantity Based Product')
    ]
    product_name = models.CharField(max_length=30, unique=True)
    product_description = models.TextField(max_length=300)
    product_price = models.DecimalField(max_digits=5, decimal_places=2)
    product_unit_weight = models.DecimalField(max_digits=5, decimal_places=2)
    product_unit_weight_units = models.CharField(max_length=2, choices=PRODUCT_UNIT_WT_CHOICES, default=Grams)
    product_type = models.CharField(max_length=3, choices=PRODUCT_TYPE_CHOICES, default=QuantityBased)
    product_image = models.ImageField(upload_to=imageUploadPath, null=True, blank=True)

    def __str__(self):
        return self.product_name

class BasketProductMapping(models.Model):
    basket_reference = models.ForeignKey(Basket, on_delete=models.CASCADE)
    product_reference = models.ForeignKey(Product, on_delete=models.CASCADE)
    mapped_basket_name = models.CharField(max_length=5,null=False, blank=False)
    mapped_product_name = models.CharField(max_length=30, null=False, blank=False)

这是我的序列化程序:

class ProductSerializer(serializers.ModelSerializer):
    product = serializers.CharField(read_only=True)
    class Meta:
        model = Product
        fields = ['id', 'product_name', 'product_description', 'product_price', 'product_unit_weight',
                    'product_unit_weight_units', 'product_type', 'product_image']

class BasketSerializer(serializers.ModelSerializer):
    basket = serializers.CharField(read_only=True)
    class Meta:
        model = Basket
        fields = ('id', 'basket_name')

class BasketProductMappingSerializer(serializers.ModelSerializer):
    basket_reference = serializers.CharField(source ='basket.basket_name', read_only=True)
    product_reference = serializers.CharField(source='product.product_name', read_only=True)
    class Meta:
        model = BasketProductMapping
        fields = ['id', 'basket_reference', 'product_reference', 'mapped_basket_name', 'mapped_product_name']

我想要实现的是在调用 BasketProductMappingSerializer 时获取“basket_name”和“product_name”中所有值的列表。但我得到的输出是这样的:

{
    "status": 1,
    "message": "Basket Product Mapping List",
    "data": [
        {
            "id": 1,
            "mapped_basket_name": "A1",
            "mapped_product_name": "XYZ"
        }
    ]
}

这是我的 views.py 代码:

class BasketProductViewSet(APIView):
    def get(self, request):
        if request.GET.get('id'):
            print('Basket Product Mapping Details')
            basketProductMappingData = BasketProductMapping.get(id = request.GET.get('id'))
            serializer = BasketProductMappingSerializer(basketProductMappingData)
        else:
            basketProductMappingData = BasketProductMapping.objects.all().values('id', 'basket_reference__basket_name', 'product_reference__product_name', 'mapped_basket_name', 'mapped_product_name')
            serializer = BasketProductMappingSerializer(basketProductMappingData, many=True)
        response = {'status':1, 'message':"Basket Product Mapping List", 'data':serializer.data}

我哪里出错了?对不起,如果我的问题很微不足道。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我看到您的视图中有错误 BasketProductMapping.get(id = request.GET.get('id')) 应该是 BasketProductMapping.objects.get(id = request.GET.get('id'))

我不知道它是否会奏效,但你可以试试吗

basket_reference = serializers.ReadOnlyField(source ='basket.basket_name')
product_reference = serializers.ReadOnlyField(source='product.product_name')

代替

basket_reference = serializers.CharField(source ='basket.basket_name', read_only=True)
product_reference = serializers.CharField(source='product.product_name', read_only=True)