django内连接查询 [英] django inner join query

查看:610
本文介绍了django内连接查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在和django一起工作,很难理解如何做复杂的查询



这是我的模型




user = models.ForeignKey(User)
tank = models.ForeignKey(TankProfile)
ts = models.DateTimeField(auto_now = True)
title = models.CharField(max_length = 50)
body = models.TextField()

class Meta:
ordering = ('-ts')
get_latest_by ='ts'

我需要拉给予坦克对象的用户名。



用户对象是django中内置的对象..谢谢!



编辑:



我已尝试过这个

  print User.objects.filter (tankjournal__tank__exact = id)

似乎没有拉出只是id ..并拉出一切tankjournal并将其与坦克对象进行匹配

解决方案

如果您已经拥有您的坦克对象,您应该可以执行以下操作:

  tank.user.username 

为了减少数据库查询,您可能需要考虑使用 select_related(),例如

  tanks = TankJournal.objects.all()。select_related()
坦克中的坦克:
username = tank.user.username

如果你有一个特定的坦克ID,那么:

  tank = TankJournal.objects.select_related()。get(id = 123456)
username = tank.user.username


I am working with django and having a hard time grasping how to do complex queries

Here is my model

class TankJournal(models.Model):
    user = models.ForeignKey(User)
    tank = models.ForeignKey(TankProfile)
    ts = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=50)
    body = models.TextField()

    class Meta:
        ordering = ('-ts',)
        get_latest_by = 'ts'

I need to pull the username given the tank object.

The user object is the one built into django.. thanks!

EDIT:

I have tried this

print User.objects.filter(tankjournal__tank__exact=id)

It seems to not pull out just the id.. and pull out everything in tankjournal and match it to the tank object

解决方案

If you already have your tank object you should be able to do:

tank.user.username

To reduce the database queries you might want to consider the use of select_related(), e.g.

tanks = TankJournal.objects.all().select_related()
for tank in tanks:
    username = tank.user.username

if you have a specific tank id then:

tank = TankJournal.objects.select_related().get(id=123456)
username = tank.user.username

这篇关于django内连接查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆