I have a model called WatchList with an object called listing which corresponds to the Listings Model through a Foreign Key. I want to be able to query through the WatchList Model to get all the listings on a user's particular watchlist and display all the objects of all the listings on a webpage. I do not want to do this using a ManyToMany Field because I just got a different part of my web application that deals with the WatchList Model to work. Is there any other way to do this?
views.py
def watchlist(request):
watchlists = WatchList.objects.filter(user=request.user)
for listing in watchlists.listing:
listings_needed = watchlists.listing()
watchlist_listing = watchlists.get(listing)
listings = Listings.objects.all().filter(watchlist_listing)
return render(request, "auctions/watchlist.html",{
"listings": listings
})
models.py
class Listings(models.Model):
CATEGORY = [
("Miscellaneous", "Miscellaneous"),
("Movies and Television", "Movies and Television"),
("Sports", "Sports"),
("Arts and Crafts", "Arts and Crafts"),
("Clothing", "Clothing"),
("Books", "Books"),
]
title = models.CharField(max_length=64)
description = models.CharField(max_length=500)
bid = models.DecimalField(max_digits=1000000000000, decimal_places=2)
image = models.URLField(null=True, blank=True)
category = models.CharField(max_length=64, choices=CATEGORY, default=None)
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
class WatchList(models.Model):
listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
This error is also occurring with the current code:
arg, value = filter_expr
TypeError: cannot unpack non-iterable function object
This error is caused by watchlist_listing = watchlists.get(listing)
.
I also tried using a for loop, but that didn't work.
CodePudding user response:
You can get all Listings for a User where there is an entry in the WatchList model by following the relationship backwards in a Listings queryset - Listings.objects.filter(watchlist__user=user)
def watchlist(request):
listings = Listings.objects.filter(watchlist__user=request.user)
return render(request, "auctions/watchlist.html",{
"listings": listings
})