osaro
osaro

Reputation: 562

How to get items from django user foreign key

How do I retrieve items from django foreign keys attached to a user account?

class product(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product_title =  models.CharField(max_length=100, blank=True)
    product_price =  models.CharField(max_length=30, blank=True)
    product_image =  models.CharField(max_length=100, blank=True)

I looked into some other stack overflow question and tried request.user.product.product_title but that just returns an Attribute error,'User' object has no attribute 'product'. I also tried request.user.product_set.all() but that just returns this queryset:

<QuerySet [<product: product object (2)>, <product: product object (3)>, <product: product object (4)>]>

I tried some other things too but I can't remember what exactly and what error those threw.

Upvotes: 0

Views: 343

Answers (1)

Walucas
Walucas

Reputation: 2578

The queryset you are getting when you do request.user.product_set.all() are all the products that has that user as FK. Now you just need to work with that.

edit 1

for product in request.user.product_set.all():
    print(product.title)

Upvotes: 1

Related Questions