0

I've created a blog post model where I'm going to add a varied number of pictures. How do I setup relations with the picture model?

In the admin panel the blog form should be displaying only pictures attached to this post. Each picture might be used in many posts.

class Post(models.Model):

    name = models.CharField(max_length=200, null=False)
    article = models.TextField(null=False)
    img = models.ManyToManyField('Picture')

class Picture(models.Model):

    def get_image_path(instance, filename):
        return os.path.join('images', str(instance.id), filename)

    picture = models.ImageField(upload_to=get_image_path, default = 'images/no-img.jpg')
Daniel Holmes
  • 1,952
  • 2
  • 17
  • 28
shmnff
  • 647
  • 2
  • 15
  • 31

1 Answers1

1

I would do it like this: The Picture model has a many-to-many field referring to Post.

class Picture(models.Model):
    posts = models.ManyToManyField('Post', related_name='pictures')
    # the rest of the code goes here...

Then you can access the list of pictures of a post by:

post = Post.objects.filter(...)
post.pictures.all()  # this is possible since I've set the related_name 
# The following can be done as default without `related_name` (and with it)
post.picture_set.all()
camelBack
  • 748
  • 2
  • 11
  • 30
erik
  • 61
  • 5
  • Should `on_delete=models.CASCADE` be used with `many-to-many` relationship? – camelBack May 07 '18 at 05:54
  • 1
    @camelBack thank you for pointing this out. Cascade delete shouldn’t be used on ManyToMany relationship. – erik May 07 '18 at 05:57
  • Guess I have to use `ForeignKey` relationship – shmnff May 07 '18 at 06:09
  • @erik no problem. I think it is important to note with regards to your answer, that the `many-to-many` relation can go both ways- which means that what @Antosha did was fine (the `many-to-many` can live in either model). – camelBack May 07 '18 at 06:14
  • @AntoshaShmonoff did you want to use cascade deletions? This post might be useful: https://stackoverflow.com/questions/3937194/django-cascade-deletion-in-manytomanyrelation – camelBack May 07 '18 at 06:14