Mustapha Mohd Sagagi
Mustapha Mohd Sagagi

Reputation: 141

How make users own their data in django

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

Answers (2)

ha-neul
ha-neul

Reputation: 3248

Try

def users_homepage(request):
    product=Product.objects.filter(merchant__user=request.user).order_by('date_added')

Upvotes: 1

Dušan Maďar
Dušan Maďar

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

Related Questions