我们如何在Django中联接两个表?

时间:2019-04-03 06:14:50

标签: python django django-models

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

谢谢

1 个答案:

答案 0 :(得分:-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