- Field type : CharField
- Field option : null vs blank, choices, default, primary_key, unique
- Relationships : Many-to-one, Many-to-many, One-to-one
- Extra fileds on many-to-many
- Meta option : ordering, verbose_name, db_table
- Model method : 아래 참조
1) Verbose field name
- Each field type, except for ForeignKey, ManyToManyField and OneToOneField, takes an optional first positional argument – a verbose name.
- If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
first_name = models.CharField(max_length=30)
first_name = models.CharField("person's first name", max_length=30)
- ForeignKey, ManyToManyField and OneToOneField require the first argument to be a model class, so use the verbose_name keyword argument:
poll = models.ForeignKey(
Poll,
on_delete=models.CASCADE,
verbose_name="the related poll",
)
2) Model method
- Define custom methods on a model to add custom “row-level” functionality to your objects. Whereas Manager methods are intended to do “table-wide” things, model methods should act on a particular model instance.
- This is a valuable technique for keeping business logic in one place – the model.
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField()
def baby_boomer_status(self):
"Returns the person's baby-boomer status."
import datetime
if self.birth_date < datetime.date(1945, 8, 1):
return "Pre-boomer"
elif self.birth_date < datetime.date(1965, 1, 1):
return "Baby boomer"
else:
return "Post-boomer"
@property
def full_name(self):
"Returns the person's full name."
return '%s %s' % (self.first_name, self.last_name)
2-1) Overriding predefined model methods
- There’s another set of model methods that encapsulate a bunch of database behavior that you’ll want to customize. In particular you’ll often want to change the way
save()
and delete()
work.
- You’re free to override these methods (and any other model method) to alter behavior.
- A classic use-case for overriding the built-in methods is if you want something to happen whenever you save an object. For example (see save() for documentation of the parameters it accepts):
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def save(self, *args, **kwargs):
do_something()
super().save(*args, **kwargs)
do_something_else()