【问题标题】:How can we join two tables in django?我们如何在 django 中加入两个表?
【发布时间】:2019-08-24 13:47:53
【问题描述】:

是否可以在 Django 中基于公共键(外键)连接两个模型(表)?如果有,请举例说明。为此,我浏览了 Django 文档。但我了解了如何在 django 中执行原始 SQL 查询。

谢谢

【问题讨论】:

  • 每个 Django 教程都比这里发布的更详细地解释了这一点。
  • @Selcuk 你能喜欢任何链接吗?对不起,我是菜鸟。

标签: python django django-models


【解决方案1】:

这是来自Django Documentation的示例:

from django.db import models

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

    class Meta:
        ordering = ('headline',)

通过此示例,您可以通过以下方式轻松联系到文章的记者:

print(article.reporter.firstname, article.reporter.last_name)

但如果您包含运行原始 SQL 查询,这里有一个示例(更多详细信息请参见 Django documentation):

from django.db import connection

def my_custom_sql(self):
    with connection.cursor() as cursor:
        cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
        cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
        row = cursor.fetchone()

    return row

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 2018-02-05
    • 2019-04-15
    • 1970-01-01
    • 2018-12-17
    • 2015-04-28
    相关资源
    最近更新 更多