Justin
Justin

Reputation: 1479

Query all objects belonging to user

I have the following two models (only included their relationship to each other). This is a job board site, a business owner can create one or more Business objects (on the off chance they own more than one small business) and then post as many Job objects as they please.

class Business(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE)
class Job(models.Model):
    business = models.ForeignKey(Business, on_delete= models.CASCADE)

How can I get all Job objects belonging to a User? I know I can get all Job objects belonging to a Business but a user can create multiple businesses.

I know I have to build some kind of chain filter, I am just not sure how to go about that.

Edit: I am trying to achieve this so I can display all of a user's posts in a dashboard type of view.

Upvotes: 0

Views: 480

Answers (1)

Dev Catalin
Dev Catalin

Reputation: 1325

You can do:

Job.objects.filter(business__user=user)

Note the double underscore after "business". That's how you access the business' attributes

Upvotes: 1

Related Questions