JD Yang
JD Yang

Reputation: 371

django : get object from foreign key

Suppose following model class,

 class Bookmark(models.Model):   
     owner = models.ForeignKey(UserProfile,related_name='bookmarkOwner')
     parent = models.ForeignKey(UserProfile,related_name='bookmarkParent')
     sitter = models.ForeignKey(UserProfile,related_name='bookmarkSitter')

How can I get sitter objects from owner Objects?

user = UserProfile.objects.get(pk=1)

UserProfile.objects.filter(bookmarkOwner=user)

returns empty tuple, and I cannot specify sitter variable.

Upvotes: 5

Views: 34191

Answers (2)

nilu
nilu

Reputation: 940

I believe you can do something like this, if you want to avoid using a loop:

pks = some_user_profile.bookmarkOwner.values_list('sitter', flat=True)
sitters = UserProfile.objects.filter(pk__in=pks).all()

Alternatively, you might want to experiment with setting up a many-to-many field and using the through parameter. See the Django docs: https://docs.djangoproject.com/en/2.0/ref/models/fields/#manytomanyfield

Upvotes: 9

Aamir Rind
Aamir Rind

Reputation: 39649

you should do

objs = Bookmark.objects.filter(owner=user)
# This will return all bookmarks related to the user profile.

for obj in objs:
    print obj.owner # gives owner object
    print obj.parent # gives parent object
    print obj.sitter # gives sitter object

If there is only one Bookmark object for a user profile (no multiple entries). Then you should use .get method instead (which return a single object).

obj = Bookmark.objects.get(owner=user)
print obj.owner
print obj.parent
print obj.sitter

Upvotes: 5

Related Questions