Skip to content
Advertisement

Using regular expression for a field name in a Django

I have a model in Django that has the fields photo_1, photo_2, photo_3 and many other fields that does not contains the “photo” string on their names. Also, the photo fields can be blank, so I can find some rows with empty photo fields. For the html template, is there a way to go through the fields named “^photo_[0-9]*$” and selecting only those that are not empty ?

Here is what I mean:

# views.py file

def listing(request, listing_id):
    listing = get_object_or_404(Listing, pk=listing_id)
    
    context = {
        'listing': listing
    }

    return render(request,"listings/listing.html", context)
# listsing.html file

    <div class="col-md-2">
        <a href="{{listing.photo_n.url}}" data-lightbox="home-images">
            <img src="{{listing.photo_n.url}}" alt="" class="img-fluid">
        </a>
    </div>

I would like to go through the “listing” QuerySet, searching for the fields named “^photo_[0-9]*$” and, if the the value for that field is not empty, pass it to ref=”{{}}” and src=”{{}}” tks

Advertisement

Answer

Usually it is not a good idea to create a model with a lot of photo_i fields: it means that the database needs to store a lot of fields where it is likely that most of them are empty, but furthermore it makes querying harder (for example finding a Listing object that contains a certain photo will result in a longe query) and furthermore likely eventually you will need a Listing with an extra photo.

In order to implement something where a Listing can have an arbitrary amount of photo’s, one makes an extra model that has a photo field, and links to a Listing object through a ForeingKey.

This thus means that the model looks like:

class Listing(models.Model):
    # no photo_i items
    # …
    pass

class ListingPhoto(models.Model):
    listing = models.ForeignKey(
        Listing,
        on_delete=models.CASCADE,
        related_name='photos'
    )
    photo = models.ImageField()

then you can render the photos with:

<div class="col-md-2">
    {% for photo in listing.photos.all %}
    <a href="{{ photo.photo.url }}" data-lightbox="home-images">
        <img src="{{ photo.photo.url }}" alt="" class="img-fluid">
    </a>
</div>
Advertisement