0👍
✅
You can super
override the save
method to enforce logic:
class Foo(models.Model):
bar = models.BooleanField(default=False)
baz = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if self.bar and self.baz:
raise SomeException()
return super(Foo, self).save(*args, **kwargs)
1👍
This would be better suited to a single field with choices
. Examples of this are clothing sizes, genders, subscription levels, etc.
class Foo(models.Model):
# store the different choices as properties for comparison later
SMALL = 'small'
BIG = 'big'
# group the choices into a list of tuples
# the first value of the tuple is how they're stored in the database
# the second value is how they're displayed to the user
SIZES = (
(SMALL, 'Small'),
(BIG, 'Big'),
)
# apply the choices to the field with a default
size = model.CharField(max_length=10, choices=SIZES, default='small')
You can then compare them in your views:
foo = Foo.objects.get(id=1)
if foo.size == Foo.SMALL:
print 'this foo is small'
This is a common pattern in Django and can represent the choices in forms using ChoiceFields
and ModelChoiceFields
. They’re also well supported in the Django Admin app and ModelForms
. These form fields can be rendered using either the dropdown select widget or radio buttons widget.
- Why do balanced Django templating {% if %} and {% endif %} get Invalid block tag on line 50: 'endif', expected 'empty' or 'endfor'
- Remapping traffic from one port to another using ATS
- How do i setup django in wamp?
- How to feed data from django into a modal?
- Django ID based dynamic URL with base64
Source:stackexchange.com