如何使用Django queryset编写下面的sql查询



我尝试了很多解决方案,但都没有找到任何运气,而且django queryset是否比原始sql联接查询更快?

Models -
class S2BotCategoriesMappings(models.Model):
id = models.IntegerField(primary_key=True)
id_s2_bot = models.ForeignKey(S2Bot, models.DO_NOTHING, db_column='id_s2_bot', blank=True, null=True)
id_s2_bot_categories = models.ForeignKey(S2BotCategories, models.DO_NOTHING, db_column='id_s2_bot_categories', blank=True, null=True)
class Meta:
managed = False
db_table = 's2_bot_categories_mappings'

class S2UserSubscription(models.Model):
id = models.IntegerField(primary_key=True)
id_s2_users = models.ForeignKey('S2Users', models.DO_NOTHING, db_column='id_s2_users', blank=True, null=True)
id_s2_bot = models.ForeignKey(S2Bot, models.DO_NOTHING, db_column='id_s2_bot', blank=True, null=True)
class Meta:
managed = False
db_table = 's2_user_subscription'
query = """
SELECT
s2_user_subscription.id_s2_users,
s2_user_subscription.id_s2_bot,
s2_bot_categories_mappings.id_s2_bot_categories
FROM  s2_user_subscription
LEFT JOIN s2_bot_categories_mappings 
ON s2_user_subscription.id_s2_bot = s2_bot_categories_mappings.id_s2_bot;
"""

此链接提供了您询问Django QuerySet与原始SQL性能考虑因素的第一个问题的答案

我从文件中找到了这个。它应该有你想要的答案。https://docs.djangoproject.com/en/4.1/topics/db/sql/更具体地说,下面的链接回答了如何在Django中将查询字段映射到模型字段,因为我知道这就是您想要做的。https://docs.djangoproject.com/en/4.1/topics/db/sql/#mapping-将查询字段转换为模型字段。我希望这能有所帮助。

最新更新