Get foreign key related data in django using filter

This is the model :

class Requirement(models.Model):
    name = models.CharField(max_length=100)
    user = models.ForeignKey(
      User,on_delete=models.CASCADE, related_name = 'user'
    )
    assigned_user = models.ForeignKey(
      User,related_name = "assigned",on_delete=models.CASCADE,
    )

I am running this query:

requirementsOb = Requirement.objects.filter(user = currentUser)

Where currentUser is logged in user. The result returns multiple requriements. I also want to get all user related data. How can i get user related data?

You can try like this:

current_user = request.user
requirements = current_user.user.all() | current_user.assigned.all()

Or you can try this approach:

requirementsOb = Requirement.objects.filter(Q(user = currentUser) | Q(assigned_user=currentUser))

If you want to get user data from requirements, you can try:

for r in requirementsOb:
    r.user
    r.assigned_user

If you want to get only the first requirement from the requirementsOb, then try like this:

requirement = requirementsOb.first() # or .last() for last object
requirement.user
requirement.assigned_user

More information can be found in documentation.

Back to Top