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:

JavaScript
JavaScript

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:

JavaScript

then you can render the photos with:

JavaScript
Advertisement