简体   繁体   中英

Related Objects Reference Django

Given the following code:

Models.py

class Advertisement(models.Model):
    title = models.CharField(null=True, blank=True, max_length=30)
    created_by = models.ForeignKey(User)

class Gallery(models.Model):
    advertisement = models.ForeignKey(Advertisement, related_name='images')
    image = models.ImageField(upload_to=image_directory_path, help_text="Your ad image (Recommended size: 1024x768)")
    creation_date = models.DateTimeField(editable=False, default=timezone.now)

Views.py

def do_foo(request):
    search_result = Advertisement.objects.all().order_by('-creation_date')

    return render(request, 'content_search.html',
                  {
                      'search_result': search_result
                  })

page.html

{% for ad in search_result %}
    {% for ad_image in ad.gallery_set %}
    <img src="{{ ad_image.image.url }}">
    {% endfor %}
{% endfor %}

How do I access the backwards relation between Advertisement and Gallery? I tried ad.gallery_set and ad.images_set but I could not get the images.

I tried to follow what they say here Django Relation Objects Reference and in this topic .

Your code has related_name="images" . So ad.images it is.

Edit: as shredding notes correctly, you can't use that directly if you want to loop over it, and need to add .all to get a queryset object:

{% for ad_image in ad.images.all %}
    <img src="{{ ad_image.image.url }}">
{% endfor %}

Maybe related name "galleries" would be a bit more clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM