views:

32

answers:

2

I have a model like this:

class database(models.Model):
  db_name = models.CharField('Name', max_length=20)
  server = models.ForeignKey(dbServer, unique=True)
  user = models.ForeignKey(User)

In my view I want to grab every database realated to the current user (has to be logged in at that point). I'm sure there is an easy way to do this, but I can't find it.

+1  A: 

Use the backwards relationship:

databases = User.database_set.all()
Daniel Roseman
+3  A: 

You could simply use:

some_user.database_set.all()

How ever I recommend trying related_name attribute, for example:

class database(models.Model):
    db_name = models.CharField('Name', max_length=20)
    server = models.ForeignKey(dbServer, unique=True)
    user = models.ForeignKey(User, related_name="databases")

And then:

some_user.databases.all()
juanefren