Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

unique mark boolean django model field

#FIELDS.py

from django.db.models import BooleanField


class UniqueBooleanField(BooleanField):
    def pre_save(self, model_instance, add):
        objects = model_instance.__class__.objects
        # If True then set all others as False
        if getattr(model_instance, self.attname):
            objects.update(**{self.attname: False})
        # If no true object exists that isnt saved model, save as True
        elif not objects.exclude(id=model_instance.id)
                        .filter(**{self.attname: True}):
            return True
        return getattr(model_instance, self.attname)

# To use with South
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^project.apps.fields.UniqueBooleanField"])


#Models.py
from django.db import models

from project.apps.fields import UniqueBooleanField


class UniqueBooleanModel(models.Model):
    unique_boolean = UniqueBooleanField()

    def __unicode__(self):
        return str(self.unique_boolean)
Comment

PREVIOUS NEXT
Code Example
Python :: tar: Exiting with failure status due to previous errors 
Python :: create model object from dictionary 
Python :: histogram plot seaborn 
Python :: python union type 
Python :: how to delete a row based on a criteria in python datafram 
Python :: generate 3 pages pdf reportlab 
Python :: python wait for executable to finish before perceeding 
Python :: python ufeff character from file 
Python :: General Loop Structure 
Python :: how to print a text in python 
Python :: how to convert a sentence into a list of words in python 
Python :: dataframe passed by reference or value 
Python :: Kivy button on press call function with arguments 
Python :: Lists and for loops 
Python :: print e 
Python :: File "<ipython-input-12-48c6c043344b", line 29 coin = random.randint(0,1) ^ IndentationError: expected an indented block 
Python :: get length of a tuple in python 
Python :: django graphene without model 
Python :: Pouring 8 litres into 2 empty container of size 3 and 5 to get 4 litre in any container 
Python :: how to create dll from java code 
Python :: torch.tensor.expand 
Python :: remove item from list python grepper 
Python :: pristine 
Python :: os.startfile on raspberry 
Python :: insert in a sorted list python 
Python :: python code to open an application 
Python :: python transpose a list 
Python :: pygame get rect 
Python :: palindrome python 
Python :: find distance between two points in python 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =