如何使用查找字段订购查询集?

How to order queryset with lookup fields?

我想用配置文件模型中的 full_name 来订购我的用户。我怎么能在这里做?

观看次数

CustomUser.objects.filter(is_active=True).order_by('profile.full_name')

型号

class Profile(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    full_name = models.CharField(max_length=255)

你看起来"through"双下划线的关系(__),所以你可以订购:

CustomUser.objects.filter(is_active=True).order_by(<b>'profile__full_name'</b>)

这将在数据库中进行 JOIN,从而在相关 profilefull_name 字段上进行排序。