开发者

Get related (via ForeignKey) object in my view

开发者 https://www.devze.com 2023-01-08 03:48 出处:网络
开发者_StackOverflow中文版I have a model like this: class database(models.Model): db_name = models.CharField(\'Name\', max_length=20)
开发者_StackOverflow中文版

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.


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()


Use the backwards relationship:

databases = User.database_set.all()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号