如何解决订购数据,django 上的分页器
我正在制作的程序是从数据库中显示有关产品的信息。 该程序运行良好,问题是我想按姓氏而不是“所有者”订购。例如。如果客户用户名是 ewOI,这是“所有者”,他的名字是罗伯特,姓氏是 Bosh,我想按姓氏而不是所有者对查询集进行排序。
这是视图代码:
class ExpView(ListView):
context_object_name = 'product'
queryset = Product.objects.filter(prod__isnull=True).order_by('owner')
template_name = 'productrecords.html'
paginate_by = 10
有两种模型,一种在产品中,一种在用户中 产品型号:
class Product(models.Model):
owner = models.ForeignKey(
User,on_delete=models.PROTECT,related_name='products'
)
id_subscription = models.CharField(max_length=30,unique=True)
amount = models.DecimalField(max_digits=11,decimal_places=2,null=True)
interest_rate = models.DecimalField(max_digits=4,decimal_places=2)
start_date = models.DateField(null=True)
以及用户模型:
class Profile(models.Model):
user = models.OnetoOneField(User,primary_key=True)
second_name = models.CharField(max_length=32,blank=True)
last_name2 = models.CharField(max_length=32,blank=True)
recovery_email = models.EmailField(unique=True,null=True)
phone_number = models.CharField(max_length=16,unique=True,null=True)
但我想 order_by('last_name') 但这不起作用。我该如何订购?
非常感谢
解决方法
您也可以在指定 order_by 参数时引用相关模型。像这样:
queryset = Product.objects.filter(prod__isnull=True).order_by('owner__profile__last_name2')
它应该可以工作。 (虽然,我想知道在 Profile 中使用 last_name2 的原因是什么,如果 User 模型有 last_name 字段。)
,你试过了吗?
queryset = Product.objects.filter(prod__isnull=True).order_by('owner__last_name2')
您可以通过键入 __ 从外键调用字段。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。