【问题标题】:How to Access Data Within Django ManytoMany with SQL Query如何使用 SQL 查询访问 Django ManytoMany 中的数据
【发布时间】:2021-07-03 19:22:22
【问题描述】:

我在一个 Django 站点中有两个模型如下,其中一个是多对多关系:

class Seller(models.Model):
  account       = models.ForeignKey(Account, related_name='sellers',null=True, on_delete=models.SET_NULL)
  bio           = models.TextField(null=True, blank=True)
  city          = models.CharField(max_length=50, null=True, blank=True)

class Account(models.Model): 
  username      = models.CharField(max_length=50, blank=True, null=True, unique=True)
  password      = models.CharField(max_length=64)
  name          = models.CharField(max_length=50, blank=True, null=True)

我正在尝试在我的 Postgresql 数据库上运行 SQL 查询,但我找不到一种清晰的方法来编写 SQL 查询以访问多对多关系中的信息。

我有卖家 ID,我想在 Account 中获取用户名。如果我尝试以下显然不正确的方法,它将无法正常工作,但我不知道下一步该做什么:

SELECT seller_seller.bio, seller_seller.account.id
FROM seller_seller, admin_account
WHERE ...no clue! 

有人能指出我正确的方向吗?谢谢!

【问题讨论】:

  • 您在两个模型中是否有共同的密钥/标识符?你说你有卖家 ID,但我想我在卖家类中没有看到?不确定它的结构,但通常如果你有一个公共密钥,你应该能够将这些表连接在一起......?你能发布postgresql表定义吗?这会很有帮助

标签: sql django postgresql many-to-many


【解决方案1】:

您可以通过以下查询简单地获取与seller_id 匹配的 Seller 对象:

>>> seller = Seller.objects.get(pk=seller_id) # Note it would raise SellerDoesNotExists if matching pk not found

然后使用上面的seller 对象,您可以通过以下方式获得username

>>> seller.account.username

但上述查询的问题是它为获取用户名做了额外的查询。

所以为了避免额外的查询,您可以使用 select_related 来执行 InnerJoin 与相关的Account

>>> from django.db.models import F
>>> seller_id = 1  # seller id that you have
>>> qs = (Seller.objects.filter(pk=seller_id).select_related('account')
                        .annotate(username=F('account__username')))
>>> print(qs.first().username)  # Note : It would raise AttributeError if no object found matching the condition. 

【讨论】:

  • 感谢您的回复!我正在尝试对数据库进行原始 SQL 查询(使用 Heroku 中的数据剪辑)。我可以在 Django 中解决这个问题,但我不知道如何在 SQL 中从多到多获取数据。你能帮忙吗?谢谢!
  • 您可以随时检查由print(qs.query) 在上面的示例中负责查询结果的原始查询,该示例基本上是内部连接。
猜你喜欢
  • 2016-09-19
  • 1970-01-01
  • 1970-01-01
  • 2010-11-03
  • 1970-01-01
  • 2015-06-23
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
相关资源
最近更新 更多