【问题标题】:How to inner join tables based on ManyToManyField and group by a parameter and get latest one in Django?如何基于 ManyToManyField 内部连接表并按参数分组并在 Django 中获取最新的表?
【发布时间】:2021-12-28 10:33:48
【问题描述】:

我有两个具有 ManyToManyField 关系的模型:

class Education(models.Model):
    title = models.CharField(default=None, max_length=100)
    content = models.TextField(default=None)
    price = models.ManyToManyField(Price)

class Price(models.Model):
    cost = models.CharField(default=None, max_length=20)
    created_at = models.DateTimeField(auto_now=True, null=True, blank=True)

我可以像这样获取所有行:

result = Education.objects.filter(price__in=Price.objects.all()).select_related('Price')/
.values_list('title', 'content', 'price__cost', 'price__created_at')

但现在我想分组 education.idcost 参数应该是最新插入的参数(基于created_at)。

所以我想列出所有Education 和最新的cost 为每个教育插入。

【问题讨论】:

    标签: django join group-by inner-join relation


    【解决方案1】:

    它对你有用吗,它会返回相应的 id

    Education.objects.filter(price__in=Price.objects.all()).select_related('Price').values('id').annotate(price_id=Max('price__id'))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      相关资源
      最近更新 更多