【问题标题】:Django Query For Max Value For Column Which Includes Foreign Key Table Also In ResultDjango查询包含外键表的列的最大值也在结果中
【发布时间】:2020-07-02 11:55:24
【问题描述】:

我有两个相关的模型 -

class Auction(models.Model):
  uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False)
  # other properties

class MaxBid(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    value = models.DecimalField(
        decimal_places=2,
        max_digits=10,
        validators=[MinValueValidator(MINIMUM_TRANSACTION_VALUE)]
    )
    created = models.DateTimeField(default=timezone.now)
    auction = models.ForeignKey(
        'Auction',
        on_delete=models.CASCADE,
        related_name='bids'
    )
    user = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
        related_name="bids"
    )

我想获得用户在拍卖中的最高出价以及 SINGLE django SQL 查询中的拍卖列。

这个 SO 问题 - SQL select only rows with max value on a column - 帮助我看到了在原始 sql 中执行此操作的方法 -

SELECT * FROM "products_maxbid" as m
JOIN "products_auction" as a on m.auction_id = a.uuid
WHERE m.uuid in (
    SELECT m.uuid FROM "products_maxbid" as m
    INNER JOIN (
        SELECT auction_id, Max(value) as value FROM "products_maxbid"
        WHERE user_id = '2'
        GROUP BY auction_id
) n
on m.auction_id = n.auction_id and m.value = n.value and m.user_id = '2'
)
ORDER BY a.square_id # can apply any orders now to the auction table like normal

我不知道从哪里开始在 Django 中实现这一点 - 好吧,显然是文档,但那里没有什么突出的。

我所做的只是 INNER JOIN 中的子查询 -

bids = MaxBid.objects.filter(user=some_user).values("auction").annotate(max=Max('value')).order_by()

当我尝试将它与filter 一起使用时,它抱怨说在同一个查询中返回了两列。所以我想第一个问题是如何像原始 SQL 那样进行 INNER JOIN?

甚至可以通过 ORM 实现吗?这个答案给了我一些希望,但我无法完全理解它 - Django: Record with max element

更新 -

我没有意识到原始 SQL 查询有多么简单,所以只有它们

【问题讨论】:

  • 过滤后请提供错误

标签: django django-orm


【解决方案1】:
#In django you must create a class and import Model , look here (example)

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Entry(models.Model):  # pass info  of your tables
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    number_of_comments = models.IntegerField()
    number_of_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline

# How can I see the raw SQL queries Django is running?

# Make sure your Django DEBUG setting is set to True. Then do this:

>>> from django.db import connection
>>> connection.queries
[{'sql': 'SELECT polls_polls.id, polls_polls.question, polls_polls.pub_date FROM polls_polls','time': '0.002'}]

# it's like "embedded queries"

【讨论】:

  • 这有什么帮助?
猜你喜欢
  • 2010-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 2011-08-10
  • 1970-01-01
相关资源
最近更新 更多