views:

120

answers:

1

I've got a ManyToManyField in a user object and it's used to map the users that user is following. I'm trying to show a subset list of who they have most recently followed. Is there a trick in .order_by() that will allow me to sort by the id of the ManyToManyField? The data is there, right?

# (people the user is following)
following = models.ManyToManyField(User, related_name="following", blank=True)

theuser.following.filter(user__is_active=True).order_by("user__id")

That will give me a list of the users the user is following but ordered by when they joined. I want the order of the following list to be in order of when the user followed them.

A: 

I am not sure whether you can achieve this with a regular ManytoManyField. You could try defining the intermediate model explicitly.

nb: Untested code!

class Person(models.Model)
    name = models.CharField(max_length=30)

class FollowerRelationship(models.Model)
    follower = models.ForeignKey(Person, related_name = following_set)
    following = models.ForeignKey(Person, related_name = follower_set)

You can then create following relationships in the shell as follows.

# Create Person objects
>>> a = Person(name="Alice")
>>> a.save()
>>> b = Person(name="Bob")
>>> b.save()
>>> c = Person(name="Chris")
>>> c.save()

# Let Alice follow Chris and Bob 
>>> FollowerRelationship.objects.create(follower=a, following=c)
>>> FollowerRelationship.objects.create(follower=a, following=b)

You can create a queryset of FollowerRelationship objects where Alice is the follower, ordered by the id of the join table, with the line:

>>> qs = FollowerRelationship.objects.filter(follower=a).order_by('id')
>>> [fr.following for fr in qs]

Note that you have to loop through the FollowerRelationship objects, to get the 'followed' Person in the relationship.

You may also want to look at Extra fields on many-to-many relationships in the Django docs, which describes how to specify the intermediate model in a many-to-many relationship.

Alasdair