django models


Author: yifei / Created: June 8, 2017, 2:28 a.m. / Modified: June 8, 2017, 10 a.m. / Edit

basic usage

using models.Model and models.SomeField

from django.db import models

class Book(models.Model)
    title = models.CharField(max_length=100, blank=True)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField(null=True, blank=True)

     def __str__(self):
         return self.title

     class Meta:
           ordering = ["name"]
           db_table = ''

notice the manytomanyfield and foreignkey field

reference to self: models.ForeignKey('self')

fat models is not all that good, it may cause god object problem

field parameters

automatic id field

by default, django gives each model a primary key field. if primary_key=True is set on any other field, django will not generate this.

meta

leave field blank

to make string field optional, just add blank = True if you want to allow blank values in a date field (e.g., DateField, TimeField, DateTimeField) or numeric field (e.g.,IntegerField, DecimalField, FloatField), you’ll need to use both null=True and blank=True.

Abstract base class

比如说有时候我们对于每一个模型都需要创建 create_time, modify_time 字段

from django.db import models

class CommonInfo(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()

    class Meta:
        abstract = True

class Student(CommonInfo):
    home_group = models.CharField(max_length=5)

others

if you want to override the __init__ method, remeber to do

def __init__(self, *args, **kwargs):
    super(models.Model, self).__init__(self, *args, **kwargs)
    # your code here

fat models is not all that good, it may cause god object problem

why not using foreign keys

you can not use foreign keys across two databases


评论区