Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try something along the lines of:</p> <pre><code># models.py class Gallery(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=200, null=True) images = models.ManyToMany(Image) class Image(models.Model): title = models.CharField(max_length=30) caption = models.CharField(max_length=200, null=True) image = models.ImageField(upload_to=SOMEPLACE_FOR_MEDIA) </code></pre> <p>From here you should be able to do things like:</p> <pre><code>image = Image.objects.get(title="Girl Holding Cheese") related_galleries = image.gallery_set.all() </code></pre> <p>or something similar as needed to pull what you want. The same goes the other way. To pull all images in a gallery you would do</p> <pre><code>gallery = Gallery.objects.get(name="Cheesy Wimmin") related_images = gallery.images.all() </code></pre> <p>Though the assignments at the end aren't necessary, I usually just pass gallery.images.all() or image.gallery_set.all() directly. Note the "_set" at the end of the reference from the object that does <em>not</em> contain the M2M definition.</p> <p>On the subject of direct usage, you can do compound references like</p> <pre><code>Image.objects.get(title="Girl Holding Cheese").gallery_set.all() </code></pre> <p>as well, but you have to decide when this makes code more clear and concise and when it just makes it more confusing to read later.</p> <p>I hope this put you in the right direction.</p> <h2>Update</h2> <p>In your comment below you noticed that you cannot do</p> <pre><code>images = Images.objects.filter(gallery_set="Cheesy Wimmins") related_galleries = images.gallery_set.all() </code></pre> <p>This is because you would be trying to filter() or all() on a queryset, not an individual model. So to make this work you can use a for loop in your template. Something like</p> <pre><code># views.py galleries = Gallery.objects.all() return render(request, 'some/template.html', {'galleries': galleries}) </code></pre> <p>And then</p> <pre><code>&lt;!-- templates/some/template.thml --&gt; {% for gallery in galleries %} &lt;div class="gallery"&gt; &lt;h2&gt;{{ gallery.name }}&lt;/h2&gt; {% for item in gallery.images.all %} &lt;div class="image"&gt; {{ item.image }} &lt;/div&gt; {% endfor %} &lt;/div&gt; {% endfor %} </code></pre> <p>or something like this. Of course, you need to do whatever formatting steps you want to make this look right, but that's a way to get at your data.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload