Login

Self Join Possible?

Author:
slacy
Posted:
November 8, 2010
Language:
Python
Version:
Not specified
Tags:
select extra self join
Score:
-2 (after 2 ratings)

Any way to compute second and third degree relations with one QuerySet?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Friend(models.Model): 
  from = ForeignKey('User', related_name='friends_of_me')
  to = ForeignKey('User', related_name='my_friends')


def first_degree(user): 
  return user.my_friends_set.all()

def second_degree(user): 
  # Totally bogus syntax below: 
  return user.my_friends_set.my_friends_set.all() 

More like this

  1. QLeftOuterJoins by dottedmag 8 years ago
  2. Left Outer join Q object by karsu 8 years, 1 month ago
  3. Slice filter by sneeu 8 years, 4 months ago
  4. Flickr Sync by bretwalker 8 years ago
  5. Model Hooks by jakecr 5 years, 5 months ago

Comments

eallik (on November 11, 2010):

You can try smth like:

User.objects.filter(friendtofriend__to=user)

#

eallik (on November 11, 2010):
User.objects.filter(friend__to__friend__to=user)

#

Please login first before commenting.