QuerySet order_by中间模型

时间:2017-01-19 15:00:07

标签: django django-queryset manytomanyfield django-intermediate-table

我正在尝试使用created字段创建一个记录下列关系时间的中间模型。

模型如下:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    realname = models.CharField(max_length=20, verbose_name='真實姓名', blank=True)
    nickname = models.CharField(max_length=20, verbose_name='暱稱/顯示名稱')

## the intermediate model is connected through following field  ##
    followings = models.ManyToManyField('self', through='FollowShip',
                                        related_name='followers', symmetrical=False,
                                        through_fields=('profile_from', 'profile_to'))

    total_followers = models.IntegerField(default=0)

    def __str__(self):
        return 'Profile of User:{}'.format(self.user.username)


class FollowShip(models.Model):
    profile_from = models.ForeignKey(Profile, related_name='follow_from_set')
    profile_to = models.ForeignKey(Profile, related_name='follow_to_set')
    created = models.DateField(auto_now_add=True, db_index=True)

    def __str__(self):
        return "{} follows {}".format(self.profile_from, self.profile_to)

    class Meta:
        unique_together = ('profile_from', 'profile_to')

工作正常。但是,当我尝试通过created模型的FollowShip字段访问QuerySet顺序时。发生错误。

manage.py shell

>>> user.profile.followings.order_by('followship__created')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/query.py", line 232, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/query.py", line 256, in __iter__
    self._fetch_all()
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/query.py", line 54, in __iter__
    results = compiler.execute_sql()
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 824, in execute_sql
    sql, params = self.as_sql()
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 369, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 47, in pre_sql_setup
    order_by = self.get_order_by()
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 293, in get_order_by
    field, self.query.get_meta(), default_order=asc))
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 553, in find_ordering_name
    field, targets, alias, joins, path, opts = self._setup_joins(pieces, opts, alias)
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 586, in _setup_joins
    pieces, opts, alias)
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1402, in setup_joins
    names, opts, allow_many, fail_on_missing=True)
  File "/Users/young/Desktop/env/strayvoice/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1327, in names_to_path
    "Choices are: %s" % (name, ", ".join(available)))
django.core.exceptions.FieldError: Cannot resolve keyword 'followship' into field. Choices are: follow_from_set, follow_to_set, followers, followings, id, nickname, realname, total_followers, user, user_id

看起来中间模型设置不正确。这样我在查询时找不到followship。 但是,我可以很好地进入双方。 例如:

>>> user.profile.followings.all()
`<QuerySet [<Profile: Profile of User:222222>, <Profile: Profile of User:333333>]>`
>>> user.profile.followers.all()
`<QuerySet [<Profile: Profile of User:222222>]>`

没有线索出了什么问题。

1 个答案:

答案 0 :(得分:1)

使用p.follow_from_set.order_by('created')

user.profile.followings表示user.profile所关注的个人资料 user.profile.followers表示已关注user.profile的个人资料 因此,user.profile.followersuser.profile.followings都会返回Profile的查询集,它们只能按Profile的字段排序,例如用户,真实姓名,昵称。

如果您想查找use.profile和order_by created后面的个人资料,您可以使用:

result = []
for profile_id in user.profile.follow_from_set.order_by('created').values('profile_to'):
    result.append(Profile.objects.get(id=profile_id))

如果有很多关注者,也许您可​​以通过以下方式优化sql:

profile_ids = user.profile.follow_from_set.order_by('created').values('profile_to')
profiles = Profile.objects.filter(id__in=profile_ids)

最后,按照profile_ids的顺序重新排序配置文件。

result = []
result_dict = {}
for profile in profiles:
    result_dict[profile.id] = profile
for id in profile_ids:
    result.append(result_dict[id])
return result

也许有更好的方法来解决问题。任何人都可以做出更好的解决方案吗?