Django Rest Framework-插入时从值获取外键ID

时间:2018-07-09 08:24:20

标签: django django-rest-framework

经过两天的搜索,我可能无法获得明确的答案,这可能是DRF最常见的事情之一:

我有以下模型:

class ProcessedStockAmounts(models.Model):
    prodName = models.ForeignKey(Productlist, on_delete=models.CASCADE, blank=False, unique=False)
    amount = models.CharField(unique=False, max_length=255)
    time = models.ForeignKey(StockTakingTimes, on_delete=models.CASCADE, blank=False, unique=False, default=1)

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

我正在通过我的API返回一个JSON对象,如下所示:

[{'prodName': 'SV1', 'amount': '1111111', 'time' : 1}]

当我插入带有值的prodName时,没有问题,但是显然我的用户将不知道prodName ID,而仅知道prod名称。因此,当我尝试插入以上内容时,出现以下错误:

ValueError: Cannot assign "'SV1'": "ProcessedStockAmounts.prodName" must be a "Productlist" instance.

This was the closest I got to an answer,当我执行以下操作时,它实际上会插入:

p = ProcessedStockAmounts(amount='33', prodName = Productlist.objects.get(productid = 'SV1'), time = StockTakingTimes.objects.get(times='06:00'))
p.save()

但是以这种方式提供数据显然会破坏目的。

我的序列化器如下所示:

class TestSerializer(serializers.ModelSerializer):

    # time = serializers.SlugRelatedField(read_only=True, slug_field='time')
    prodName = serializers.CharField()
    # prodName = serializers.SlugRelatedField(read_only=True, slug_field='prodName')

    class Meta:
        model = ProcessedStockAmounts
        fields = ('prodName','amount','time')

我认为:

class InsertMultiProcessedStock(APIView):

    def post(self, request, format='json'):
        serializer = TestSerializer(data = request.data, many=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else: 
            return Response(serializer.errors)

产品列表型号:

class Productlist(models.Model):
    productid = models.CharField(unique=True, max_length=20)  # Field name made lowercase.
    proddescription = models.CharField(db_column='prodDescription', max_length=255, blank=True, null=True)  # Field name made lowercase.
    packaging = models.ForeignKey(Packaging, on_delete=models.CASCADE, blank=True, null=True)
    unitweight = models.FloatField(db_column='unitWeight', blank=True, null=True)  

    def __str__(self):
        return self.productid

2 个答案:

答案 0 :(得分:2)

如果您有相关的型号,这会更加容易。但是注释掉的slugrelatedfield是使用实际字段名称的方式:

prodName = serializers.SlugRelatedField(read_only=False, slug_field='productid')

答案 1 :(得分:0)

您的序列化器错误,必须使用关系序列化器。

prodName = ProductlistSerializer(许多= False)

但是我发现您的模型定义非常混乱