简体   繁体   中英

Django-Filter: ModelChoiceFilter using queryset related to the current user

I am using Django-Filter library.

I have 2 models, Listing and ListingReview . I would like to be able to create a filter for the ListingReview model, so that people can select which Listing they want to see reviews for.

# models.py:
class Listing(models.Model):
    posted_by = models.ForeignKey('auth.User', related_name='listings', on_delete=models.CASCADE)

class ListingReview(models.Model)
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='listing_reviews') 


# filters.py

def listings(request):
    # if request is None:
    #     return Listing.objects.none()
    return Listing.objects.filter(posted_by=request.user)


class ListingReviewFilter(django_filters.FilterSet):
    listing = django_filters.ModelChoiceFilter(
        name='listing', lookup_expr='isnull',
        empty_label='All listings',
        queryset=listings,
    )

    class Meta:
        model = ListingReview
        fields = ['listing']

However, I don't understand why request is None , I get:

'NoneType' object has no attribute 'user'

What I need: For a given user , find the associated Listings using: Listing.objects.filter(posted_by=user) and pass it to the queryset parameter in the filter eg dynamically define the queryset based on current user. Since every user owns a different set of listings.

尝试调用此方法时,是否在客户端请求中发送了参数user

How about using a custom filter method

class ListingReviewFilter(django_filters.FilterSet):
    listing = django_filters.ModelChoiceFilter(
        name='listing',
        lookup_expr='isnull',
        empty_label='All listings',
        queryset=Listing.objects.all(),
        method='filter_listing',
    )

    class Meta:
        model = ListingReview
        fields = ['listing']

   def filter_listing(self, queryset, name, value):
       return queryset.filter(posted_by=self.request.user)

I don't understand what is your problem but your idea and in specific your problem solved my problem. In other words, I've done the exactly same thing as you have done and it worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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