Home > Net >  Query in Django to sort in one table based on result of another table
Query in Django to sort in one table based on result of another table

Time:10-30

I have two models listing model is:

class listing(models.Model):
    productTitle= models.CharField(max_length=60)
    description = models.TextField()
    category = models.ForeignKey(category,on_delete=models.CASCADE,null=True)
    productPrice = models.FloatField(default=0.0)
    
    def __str__(self):
        return self.productTitle

my watchlist model is:

    item = models.ForeignKey(listing, on_delete= models.CASCADE)
    watchlist = models.BooleanField(default=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.item

In my index.html I want to show the list item if watchlist attribute is False.

Now, my views.py for index.html is as follows:

def index(request):
    if request.user != "AnonymousUser":
        items= listing.objects.exclude(id=watchlist.objects.filter(user=request.user))
    else:
        items = watchlist.objects.all()
    context = {'items':items}
    return render(request, "auctions/index.html", context)

I couldn't filter the items on listing models based on the result of watchlist model i.e if watchlist=True then I do not want to render items on index.html. Because, I want to render watchlist items in separate pages. How to query in django if there are two models used?

CodePudding user response:

You could have probably do something like this

watch_list = watchlist.objects.filter(wishlist=False, user=request.user.id).values('item')

Then if you want to fetch items, you do like this

items = listing.objects.filter(id__in=watch_list)

CodePudding user response:

from django.db.models import Q    
items = listing.objects.filter(watchlist__isnull=True) | listing.objects.filter(Q(watchlist__user=request.user) & Q(watchlist__watchlist=False))

If my understanding is correct you need to list items which are not in watchlist table too. You could use backwards relation in query. watchlist__isnull=True is for listing the entries not in watchlist table. The second part listing.objects.filter(Q(watchlist__user=request.user) & Q(watchlist__watchlist=False) is the watchlist filter

  • Related