我有商品模型:
class Commodity(models.Model):
shop = models.ForeignKey(Shop, related_name='commodity', on_delete=models.CASCADE)
brand = models.ForeignKey(Brand, blank=True, null=True, on_delete=models.CASCADE)
price_old = models.DecimalField(max_digits=10, decimal_places=2)
price_new = models.DecimalField(max_digits=10, decimal_places=2)
我尝试使用limit_choices_to
,但没有用。
我有一个序列化器:
class CommoditySerializer(serializers.ModelSerializer):
image = CommodityImageSerializer(many=False)
def get_queryset(self):
user = self.context['request'].user
queryset = Commodity.objects.filter(shop__company__user=user)
return queryset
class Meta:
model = Commodity
fields = ('id', 'shop', 'brand', 'price_old', 'price_new')
此get_queryset也无济于事。 最后,我有一个常规的CreateAPIView,并且此方法也无济于事。 如何限制外键的使用?我只需要在用户的商店内为用户创建商品。谢谢!
答案 0 :(得分:2)
我想您可以为此简单地实现validate_shop
方法:
class CommoditySerializer(serializers.ModelSerializer):
image = CommodityImageSerializer(many=False)
def validate_shop(self, value):
user = self.context['request'].user
if value.company.user == user:
return value
raise serializers.ValidationError('Invalid shop!')
class Meta:
model = Commodity
fields = ('id', 'shop', 'brand', 'price_old', 'price_new')