Search code examples
djangomodels

Django model variables - Unique


I am terribly sorry for the crummy title to this question. I can't think of how to phrase it in a simple context.


I am making a simple photo gallery. The admin can create a gallery page and upload images to it. For each gallery I want there to be a single banner image from one of the photos. The Photo model has a CharField which will tell if its a banner or not. Is there a way to make the variable to allow only one 'B' for every photo that belongs to a Gallery?


Solution

  • You should define a unique_together variable for your class. If names of your fields are album and banner, you should add this line to Meta class of your model.

    unique_together = (("album", "banner"),)
    

    Django Documents, unique-together

    And i think, using charfield for a boolean value isn't a correct choice. You should change your banner field as BooleanField.