views:

1117

answers:

2

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

+4  A: 

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
+1  A: 

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.

Jarret Hardie
each user can have multiple tanks.. and each tank can have multiple journal entries.. is the correct way to remove the User object from the tankJournal model or?
Mike
If each tank can have multiple journal entries, then each tank can also have (potentially) multiple users. If you need to narrow it to just a single user, you'll need some other parameter. Whether you start from the TankJournal or User will probably depend on what that parameter is.
Jarret Hardie