django按相关字段排序 [英] django order by related field

查看:571
本文介绍了django按相关字段排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过相关字段对联系人的QuerySet进行排序。但我不知道如何。
我这样尝试过,但它不起作用。

I want to sort a QuerySet of contacts by a related field. But I do not know how. I tried it like this, but it does not work.

foundContacts.order_by("classification.kam")

实际上,在模板中,我可以通过contact.classification.kam访问联系人的kam值,因为它是一个OneToOne关系。

Actually in a template I can access the kam value of a contact through contact.classification.kam since it is a OneToOne relationship.

(简化)模型如下所示:

The (simplified) models look like this:

class Classification(models.Model):
    kam = models.ForeignKey(User)
    contact = models.OneToOneField(Contact)

class Contact(models.Model):
    title = models.ForeignKey(Title, blank=True, null=True)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)


推荐答案

应该是:

foundContacts.order_by("classification__kam")

以下是Django文档关于进行跨越关系的查询的链接: http://docs.djangoproject.com/en/1.1/topics/db/queries /#lookups-that-span-relationships

Here is a link for the Django docs on making queries that span relationships: http://docs.djangoproject.com/en/1.1/topics/db/queries/#lookups-that-span-relationships

您还可以在 order_by 中查看一些示例参考:

https://docs.djangoproject.com/en/1.6/ref/models/querysets/#django.db.models.query.QuerySet.order_by

You can also see some examples in the order_by reference:
https://docs.djangoproject.com/en/1.6/ref/models/querysets/#django.db.models.query.QuerySet.order_by

这篇关于django按相关字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆