我正在使用django-filter,我有兩個模型CustomUser和Shop. 如何更改過濾器選擇查詢集以便用戶(request.user)只能過濾他的商店?用戶class CustomUser(AbstractBaseUser, PermissionsMixin): shop = models.ManyToManyField(Shop, blank=True, related_name='custom_user')店鋪class Shop(models.Model): address = models.CharField(_('Address'), unique=True, max_length=64, blank=False, null=False, db_index=True)過濾器.pyshops = Shop.objects.filter(is_active=True)SHOP_CHOICES = [('All', 'All')]for x in shops: SHOP_CHOICES.append((x.address, x))SHOP_CHOICES = tuple(SHOP_CHOICES)class ShopFilter(django_filters.FilterSet): address = django_filters.MultipleChoiceFilter(choices=SHOP_CHOICES) class Meta: model = Shop fields = ['address']視圖.pyf = ShopFilter(request.GET)
1 回答

尚方寶劍之說
TA貢獻1788條經驗 獲得超4個贊
qs
您可以在使用該方法返回之前過濾查詢集。
請參閱過濾主要的 `qs。
所以在你的情況下,你應該能夠說:
@property
def qs(self):
parent = super().qs
owner = getattr(self.request, 'user', None)
return parent.filter(custom_user=owner)
尚未對此進行測試,但如果您想對查詢進行任何修改,這絕對是一種方法。
添加回答
舉報
0/150
提交
取消