Monday, July 2, 2012

obtaining first/last names from Profile[class] but for those who are Friends[class]

Hopefully I can explain this properly... tldr: I need to create a page of "my friends", which needs to display first and last name from a user's profile, but listed in alphabetical order by first name.
So I need to grab the list of friends (from Friendship class), then somehow organize them by the Profile[class]'s field of "first_name". 

I have the following models:

class Profile(models.Model):
user = models.ForeignKey(User)
first_name = models.TextField(max_length=50)
last_name = models.TextField(max_length=50)

class Friendship(models.Model):
        friend          = models.ForeignKey(User, related_name='friend1')
        friendwith      = models.ForeignKey(User, related_name='friend2')

def get_friends_of(person):
        #person is a user object
        fl = Friendship.objects.filter(friend=person)
        return fl

If I use the get_friends_of() function, I am returned a list of objects, each being a "Friendship" object of those the person is friends with.

I'm confused, because at the moment, I can only get a user's name from that list by calling fl[0].friendwith.get_profile().first_name, but I'm stuck on organizing them by first name.

I'm starting to think I should be calling Profile objects, somehow specifying I only want those who have a Friendship.objects.filter(somehow saying friend=user)

What kills me is I can write the SQL query by hand... it would be exactly like this::

I'd need to do the following to get a list of Keith's friends, ordered ASC by first_name.

dude = int(User.objects.get(username='godric').pk), results to 30
select profiles_profile.first_name,profiles_profile.last_name FROM profiles_profile, friends_friendship WHERE profiles_profile.user_id = friends_friendship.friendwith_id AND friends_friendship.friend_id = 30 ORDER BY first_name ASC;

How in the djangohell am I supposed to get this using python?

Any help is VERY appreciated! (never used a Google group before)!

- Keith

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/eXRxYDHnj5MJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment