Django Model managers and properties

from django.db import modelsclass User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
def __str__(self):
return self.name
from app1.models import Useruser = User(name="xxx", email="xxx@xxx.xxx")
user.save()
from app1.models import Useruser = User.objects.create(name="xxx", email="xxx@xxx.xxx")
from django.db.models import Model, Managerclass User(Model):
....
....
objects = Manager() # The default Manager.
from django.db import modelsclass BookManager(models.Manager):
def title_count(self, keyword):
return self.filter(title__icontains=keyword).count()
class Book(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
num_pages = models.IntegerField(blank=True, null=True)
objects = BookManager() # The Custom Manager. def __unicode__(self):
return self.title
from django.db import modelsclass Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def _get_full_name(self):
return '%s %s' % (self.first_name, self.last_name) # Returns the person's full name.
full_name = property(_get_full_name)

def __unicode__(self):
return self.full_name
person = Person.objects.get(first_name='xyz', last_name='abc')person.full_name  # Note this isn't a method -- it's treated as an attribute, It returns 'xyz abc'

The article was originally published at MicroPyramid blog.

--

--

--

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Speed Up Your SQL Database

How We Build Our Facial Recognition Ferris Wheel

Git Monorepos with Github Actions

IERC721Receiver interface: migrating Solidity (Ethereum) contracts to TAKAMAKA.

How to Pass Extra Context Data to Serializers in Django-Rest-Framework

Advocating Pair Programming

All In One Filter

Text Portrait using CSS😎

Image showing text portrait using just CC

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
MicroPyramid

MicroPyramid

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company

More from Medium

Python : Django Web Framework

Docker zing a Python Django Web App on Ubuntu

Quick guide to the Python web framework Django