Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django : get object from foreign key

Tags:

django

model

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.

like image 231
JD Yang Avatar asked Dec 27 '22 12:12

JD Yang


2 Answers

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
like image 29
Aamir Rind Avatar answered Jan 03 '23 11:01

Aamir Rind


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

like image 120
nilu Avatar answered Jan 03 '23 09:01

nilu