简体   繁体   English

如何更改过滤器查询集取决于用户

[英]How to change filter queryset depends on user

I am using django-filter and I have two models CustomUser and Shop .我正在使用django-filter ,我有两个模型CustomUserShop How to change filter choices queryset so that user( request.user ) can filter only his shops?如何更改过滤器选择查询集,以便用户( request.user )只能过滤他的商店?

User用户

class CustomUser(AbstractBaseUser, PermissionsMixin):
    shop = models.ManyToManyField(Shop, blank=True, related_name='custom_user')

Shop店铺

class Shop(models.Model):
    address = models.CharField(_('Address'), unique=True, max_length=64, blank=False, null=False, db_index=True)

filters.py过滤器.py

shops = 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']

views.py视图.py

f = ShopFilter(request.GET)

You can filter the queryset before it's returned using the qs method.您可以使用qs方法在返回之前过滤查询集。

See Filtering the primary `qs.请参阅过滤主要的 `qs。

So in your case, you should be able to say:所以在你的情况下,你应该能够说:

@property
def qs(self):
    parent = super().qs
    owner = getattr(self.request, 'user', None)

    return parent.filter(custom_user=owner)

Haven't tested this, but this is definitely the method if you want to make any modifications to the query.尚未对此进行测试,但如果您想对查询进行任何修改,这绝对是一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM