django-在QuerySet结果中订购Manytomanyfield

发布于 2025-01-20 21:32:42 字数 557 浏览 4 评论 0 原文

简化模型:

Class Product(models.Model):
    name = models.CharField(max_length=250)
    launch_date = models.DateField(blank=True)

Class Collection(models.Model):
    name = models.CharField(max_length=250)
    products = models.ManyToManyField(Product, related_name="collections", blank=True)

假设我想返回一个 Collection 查询,但我希望使用此查询集返回的产品按 launch_date 排序,我该怎么做?

仅在查询中添加产品发布日期的 order_by 不起作用,因为这只是对集合进行排序,但实际上并没有对集合中的产品进行排序 Collections.objects.order_by('products__launch_date').all()

Simplified Models:

Class Product(models.Model):
    name = models.CharField(max_length=250)
    launch_date = models.DateField(blank=True)

Class Collection(models.Model):
    name = models.CharField(max_length=250)
    products = models.ManyToManyField(Product, related_name="collections", blank=True)

Say I want to return a Collection query but I want products returned with this queryset to be ordered by launch_date, how would I do this?

Just adding order_by on products launch dates to the query does not work as that just orders the collections, but doesn't actually order the products within the collections
Collections.objects.order_by('products__launch_date').all()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦忆晨望 2025-01-27 21:32:42

您可以使用 prefetch_lated 来优化数据库查询如果添加 Prefetch 对象对此您可以更改用于预取的查询集(包括排序)

qs = Collection.objects.prefetch_related(
    Prefetch('products', queryset=Product.objects.order_by('launch_date'))
)

如果始终需要此排序,您也可以将默认排序添加到模型中

class Product(models.Model):

    ...

    class Meta:
        ordering = ['launch_date']

You can use prefetch_related to optimise DB queries by fetching all related objects in a single query, if you add Prefetch objects to this you can change the queryset used to prefetch including the ordering

qs = Collection.objects.prefetch_related(
    Prefetch('products', queryset=Product.objects.order_by('launch_date'))
)

You could also just add default ordering to the model if this ordering is always desired

class Product(models.Model):

    ...

    class Meta:
        ordering = ['launch_date']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文