5

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.

Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
JD Yang
  • 371
  • 2
  • 3
  • 16

2 Answers2

9

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

pawas kr. singh
  • 416
  • 1
  • 4
  • 12
nilu
  • 940
  • 8
  • 17
  • there is no need for `.all()` at the end of `sitters = UserProfile.objects.filter(pk__in=pks).all()` – Aamir Rind Dec 23 '12 at 14:13
  • Brilliant answer! Plus I used this method because I couldn't easily update a ManyToMany field easily – Brian Mar 13 '21 at 18:34
5

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
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
  • Thanks . But is there any other way of no-using for loop? – JD Yang Dec 23 '12 at 13:23
  • Is the bookmark table contains only one Bookmark object related to profile? – Aamir Rind Dec 23 '12 at 13:25
  • yes, parent can have many bookmarks, sitter can have many bookmarks, but for one parent - one sitter pair, there is only one bookmark – JD Yang Dec 23 '12 at 13:28
  • please check my updated answer `how to retrieve a single object`. for one parent one sitter pair you should do `Bookmark.objects.get(owner=user, sitter=other_user)`. – Aamir Rind Dec 23 '12 at 13:34