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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With