mercredi 30 décembre 2020

Django: Filter ListView on currently logged-in user (manytomanyfield)

I'm working on a django project, and as I'm quite new to this framework and backend in general, I'm having a hard time finding out how to do this.

I'm building a ListView that is used to display a list of products in a template. However, I need it to only display the products made available on the site by the dealer who's currently logged in. So in other words, just a page where a dealer can see what products they've put on our site.

Here's my view:

class ArticleListView(ListView, LoginRequiredMixin):
    template_name = "accounts/list_articles.html"
    model = Product
    
    def get_context_data(self,**kwargs):
        context = super().get_context_data(**kwargs)
        context["website"] = Website.objects.first()
        context["product_list"] = context["product_list"].filter(published=True)
        return context
    

Here's the Products and Dealers models (only the relevant parts):

class Product(models.Model, CloneMixin):
    published = models.BooleanField(null=True,blank=True, default=False)
    title = models.CharField(null=True,blank=True,max_length=100)
    subtitle = models.CharField(null=True,blank=True,max_length=200)
    (...)
    dealer = models.ManyToManyField(Dealer, null=True,editable=True,related_name="product_to_dealer")
    (...)
    # Not sure what this does:
   _clone_many_to_many_fields = ['parameter', 'tag', 'category', 'dealer','images']
    (...)

    
class Dealer(models.Model, CloneMixin):
    dealer_check = models.ForeignKey("self",null=True, blank=True, on_delete=models.SET_NULL)
    published = models.BooleanField(null=True,blank=True, default=True)
    (...)
    users = models.ManyToManyField(User,null=True,blank=True, related_name='dealers')
    (...)

As it is, my ListView just displays every products there is in the db. From what I've understood, I need something like

def get_queryset(self):
        return Product.objects.filter(user=self.request.user)

or in the get_context_data, it would do the same I guess:

context["product_list"] = context["product_list”].filter(user=self.request.user)

But in this case, the user related to the product is in the Dealer model (ManyToManyField in the Product model). I want to ask django "Show me only the products for which the current logged-in user is in the "users" of the dealer related to this product."

I don't think that's too complicated by I need some pointers on this. Thanks for your help.




Aucun commentaire:

Enregistrer un commentaire