我想用HTML显示出版物的城市、州和国家的名称。但它们在不同的表中。
这是我的模特.py

class country (models.Model):
    country_name = models.CharField(max_length=200, null=True)
    country_subdomain = models.CharField(max_length=3, null=True)
    def __str__(self):
        return self.country_name

class countrystate (models.Model):
    state_name = models.CharField(max_length=200, null=True)
    country = models.ForeignKey(country, on_delete=models.CASCADE, null=True)
    importance = models.IntegerField(null=True)
    def __str__(self):
        return self.state_name

class city (models.Model):
    city_name = models.CharField(max_length=200, null=True)
    countrystate = models.ForeignKey(countrystate, on_delete=models.CASCADE, null=True)
    def __str__(self):
        return self.city_name

class publication(models.Model):
    user = ForeignKey(users, on_delete=models.CASCADE, null=False)
    title= models.CharField(max_length=300, null=True)
    country=models.ForeignKey(country, on_delete=models.CASCADE, null=True)
    countrystate=models.ForeignKey(countrystate, on_delete=models.CASCADE, null=True)
    city=models.ForeignKey(city, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.title

这是我的观点。
def publications(request):
    mypublications = publication.objects.filter(user_id=request.session['account_id'])
    dic.update({"plist": mypublications })
    return render(request, 'blog/mypublications.html', dic)

在Django视图中,下一个SQL查询的等价物是什么?
SELECT p.user_id, p.title, c.cuntry_id, c.country_name, s.state_id, s.state_name, y.city_id, y.city_name FROM publication AS p
INNER JOIN country AS c ON c.id = p.country_id
INNER JOIN countrystate AS s ON s.id = p.countrystate_id
INNER JOIN city AS y ON y.id = p.city_id

最佳答案

您可能正在寻找select_related这是实现这一目标的自然方法:

pubs = publication.objects.select_related('country', 'country_state', 'city')

您可以通过str(pubs.query)检查得到的SQL,这将导致沿着以下行出现sth(示例来自Postgres后端):
SELECT "publication"."id", "publication"."title", ..., "country"."country_name", ...
FROM "publication"
INNER JOIN "country" ON ( "publication"."country_id" = "country"."id" )
INNER JOIN "countrystate" ON ( "publication"."countrystate_id" = "countrystate"."id" )
INNER JOIN "city" ON ( "publication"."city_id" = "city"."id" )

然后将返回的光标值转换为适当的ORM模型实例,这样当您循环这些发布时,就可以通过它们自己的对象访问相关表的值。但是,这些沿着预先选定的转发关系进行的访问不会导致额外的数据库命中:
{% for p in pubs %}
     {{ p.city.city_name}}  # p.city has been populated in the initial query
     # ...
{% endfor %}

关于python - 如何在django中进行内部加入?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48128714/

10-10 04:31