12

ユーザー オブジェクトに ManyToManyField があり、ユーザーがフォローしているユーザーをマップするために使用されます。最近フォローした人のサブセット リストを表示しようとしています。ManyToManyField の ID でソートできるようにする .order_by() のトリックはありますか? データはありますよね?

# (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")

これにより、ユーザーがフォローしているが、参加したときに並べ替えられたユーザーのリストが表示されます。次のリストの順序を、ユーザーがフォローしたときの順序にしたい。

4

4 に答える 4

0

通常のでこれを達成できるかどうかはわかりませんManytoManyField。中間モデルを明示的に定義してみることができます。

nb:テストされていないコード!

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)

次に、次のようにシェルで次の関係を作成できます。

# 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)

FollowerRelationship次の行を使用して、結合テーブルのID順に並べられた、アリスがフォロワーであるオブジェクトのクエリセットを作成できます。

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

FollowerRelationship関係で「フォロー」を取得するには、オブジェクトをループする必要があることに注意してくださいPerson

また、多対多の関係で中間モデルを指定する方法を説明しているDjangoドキュメントの多対多の関係に関する追加フ​​ィールドを確認することもできます。

于 2009-12-15T23:28:03.753 に答える