简体   繁体   English

我们如何在 Django 中加入两个表?

[英]How can we join two tables in django?

Is it possible to join two models(tables) based on a common key(foreign key) in Django?是否可以基于 Django 中的公共键(外键)连接两个模型(表)? If so, please explain it with an example.如果是这样,请举例说明。 I went through the Django documentation for this.我为此浏览了 Django 文档。 But I landed on how to perform raw SQL queries in django.但是我了解了如何在 Django 中执行原始 SQL 查询。

Thanks谢谢

Here is an example from Django Documentation :这是Django 文档中的一个示例:

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',)

With this example you can easily reach article's reporter by:通过此示例,您可以通过以下方式轻松联系文章的记者:

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

But if you consist of running raw SQL queries, here is an example (more details on Django documentation ):但是,如果您运行原始 SQL 查询,这里有一个示例(有关Django 文档的更多详细信息):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM