django inner join query

China☆狼群 提交于 2019-12-01 09:05:54

问题


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


回答1:


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



回答2:


I may be misunderstanding your question, but a request on User.objects.filter() will return a list of User objects, not User ids. What you've written looks technically correct.

Remember, though, that the model you have sets up a one-to-many between the TankProfile object and the TankJournal. In other words, a single TankProfile can be associated with more than one TankJournal, and therefore to more than one user. Given this, you're query is doing the right thing, returning more than one User.



来源:https://stackoverflow.com/questions/610891/django-inner-join-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!