Django REST:通过UUID查找序列化程序

时间:2018-09-25 22:23:18

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

我正在Django REST中创建此简单的购物API。

内部,我将ID用于外键约束,而guuids被带到了外界。

对于结帐过程,用户提供了他愿意购买的商品ID列表。 POST数据中的对象因此如下所示:

{
  assets: [
    {
       'product': 'd9d5044d-2284-4d15-aa76-2eee3675035b',
       'amount': 4
    },
    ....
  ]
}

我正在使用以下票证/资产模型:

# Ticket
class Ticket(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='tickets', on_delete=models.CASCADE)


# Assets
class Asset(models.Model):
    ticket = models.ForeignKey(Ticket, related_name='assets', on_delete=models.CASCADE)
    stock_item = models.ForeignKey(Stock, related_name='stock_item', on_delete=models.SET_NULL, null=True)
    amount = models.IntegerField(validators=[MinValueValidator(0)])

序列化程序如下所示:

# Asset serializer
class AssetSerializer(serializers.ModelSerializer):

    class Meta:
        model = Asset
        fields = ('stock_item', 'amount')


# Ticket serializer
class TicketSerializer(WritableNestedModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    assets = AssetSerializer(many=True)

    class Meta:
        model = Ticket
        fields = ('uuid', 'owner', 'assets', )

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

发布上面指定类型的对象时,会出现以下错误:

{"assets":[{"stock_item": ["Invalid type. Expected PK, received string"]}]}

我似乎无法解决,我如何指示序列化程序使用uuid作为查找值?我通过使用lookup_field成员在视图级别上解决了类似的问题,但这似乎无法解决。有什么建议吗?
在此处输入代码

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,那么SlugRelatedField应该能够找到正确的相关对象。

class AssetSerializer(serializers.ModelSerializer):
    ticket = serializers.SlugRelatedField(
        read_only=True,
        slug_field='uuid',
        queryset=Ticket.objects.all() # Might be redundant with read_only=True
    )

    class Meta:
        model = Asset
        fields = ('ticket', 'stock_item', 'amount')