我有一个简单的ModelSerializer:
class OfferSerializer(serializers.ModelSerializer):
class Meta:
model = Offer
fields = ('id', 'accepted', 'comment', 'status', 'item_given', 'item_received')
使用这个模型:
class Offer(models.Model):
accepted = models.BooleanField()
status = models.BooleanField()
comment = models.CharField(max_length=1000)
creation_date = models.DateTimeField("date published", default=timezone.now)
item_given = models.ForeignKey("items.Item", related_name='item_given', on_delete=models.CASCADE)
item_received = models.ForeignKey("items.Item", related_name='item_received', on_delete=models.CASCADE)
def __str__(self):
return self.comment
以下视图使用它:
class OfferViewSet(viewsets.ModelViewSet):
queryset = Offer.objects.all()
serializer_class = OfferSerializer
外键item_given是另一个名为Item的模型,它在用户上有一个外键。
在django rest框架的生成表单中,我可以在创建新商品时为item_given字段选择任何商品。但我希望能够只选择外键用户等于request.user。
的项目我尝试在序列化程序中编辑def_queryset但没有成功。 我怎样才能做到这一点?
我的帐户中没有创建任何商品,但我收到了所有商品。
https://i.stack.imgur.com/bVfxo.png
目前我已使用ID为
的用户登录{
id: 1,
name: "asasd",
description: "sdffsd",
price_min: 123,
price_max: 234,
creation_date: "2016-11-15T17:35:11Z",
archived: false,
owner: 1,
category: 1,
image_set: [ ]
},
{
id: 2,
name: "sdfsdffiss",
description: "fsdfsd",
price_min: 124,
price_max: 1245,
creation_date: "2016-11-15T19:39:02.225543Z",
archived: false,
owner: 1,
category: 1,
image_set: [ ]
},
{
id: 8,
name: "Test",
description: "Test",
price_min: 123,
price_max: 234,
creation_date: "2016-11-15T20:42:34.492041Z",
archived: false,
owner: 3,
category: 1,
image_set: [
5
]
}
当我去创建新优惠时,每个项目都会显示在item_given字段中
答案 0 :(得分:1)
您的意思是get_queryset
并且它不是序列化方法,它是一种视图集方法。因此,您将拥有类似的内容:
class OfferViewSet(viewsets.ModelViewSet):
serializer_class = OfferSerializer
def get_queryset(self):
return Offer.objects.filter(item_given__owner=self.request.user)
答案 1 :(得分:0)
我无法解决显示每个项目的表单,但如果该项目不属于用户,我可以提出错误
def validate(self, data):
if self.context['request'].user.userprofile != data['item_given'].owner:
raise serializers.ValidationError("Item given is not owned by the current user")
return data