django - Get the set of objects from Many To One relationship

后端 未结 2 1631
长发绾君心
长发绾君心 2021-02-07 04:01

Please have a look at these models:

class Album(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=200)
    pub_date = mode         


        
2条回答
  •  天涯浪人
    2021-02-07 04:28

    Even better, you can write, in Photo

    album = models.ForeignKey(Album, related_name='photos', default=3)
    

    The photos will be the name of the reverse field from Album to Photo. If you don't define it, the reverse field will be named photo_set.

    You then use

    t_album.photos.all()  # only if you've defined the `related_name` argument to 'photos'
    

    or

    t_album.photo_set.all()
    

提交回复
热议问题