Classes are "first class" objects in Python, meaning they can be passed around and manipulated just like all other objects.
Models are classes -- you can tell from the fact that you create new models using class statements:
class Person(models.Model):
last_name = models.CharField(max_length=64)
class AnthropomorphicBear(models.Model):
last_name = models.CharField(max_length=64)
Both the Person
and AnthropomorphicBear
identifiers are bound to Django classes, so you can pass them around. This can useful if you want to create helper functions that work at the model level (and share a common interface):
def print_obj_by_last_name(model, last_name):
model_name = model.__name__
matches = model.objects.filter(last_name=last_name).all()
print('{0}: {1!r}'.format(model_name, matches))
So print_obj_by_last_name
will work with either the Person
or AnthropomorphicBear
models. Just pass the model in like so:
print_obj_by_last_name(model=Person, last_name='Dole')
print_obj_by_last_name(model=AnthropomorphicBear, last_name='Fozzy')