Reputation: 141
Currently, if you’re logged in, you’ll be able to see all the products, no matter which user you’re logged in as.how can i show merchants only the products that belongs to them.
i try this
views.py
def users_homepage(request):
product=Product.objects.filter(merchant=request.user).order_by('date_added')
and i get this error " Cannot query "mustapha": Must be "Merchant" instance"
my models.py
class Merchant(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True)
class Product(models.Model):
merchant=models.ForeignKey(Merchant, on_delete=models.CASCADE)
date_added = models.DateTimeField(auto_now_add=True)
Upvotes: 1
Views: 45
Reputation: 3248
Try
def users_homepage(request):
product=Product.objects.filter(merchant__user=request.user).order_by('date_added')
Upvotes: 1
Reputation: 9869
Use user to get a merchant instance and the use that to query products.
def users_homepage(request):
merchant = Merchant.objects.get(user=request.user)
product = Product.objects.filter(merchant=merchant).order_by('date_added')
Another way to do this is using [default] related name.
def users_homepage(request):
product = Product.objects.filter(merchant=request.user.merchant).order_by('date_added')
Upvotes: 1