Specific use of Django's models model

  • 2021-07-18 08:28:58
  • OfStack

Common Fields for model


V=models.CharField(max_length=None[, **options])              #varchar
V=models.EmailField([max_length=75, **options])              #varchar
V=models.URLField([verify_exists=True, max_length=200, **options])              #varchar
V=models.FileField(upload_to=None[, max_length=100, **options])              #varchar
#upload_to Specifies that the save directory can be formatted, 
V=models.ImageField(upload_to=None[, height_field=None, width_field=None, max_length=100, **options])
V=models.IPAddressField([**options])              #varchar
V=models.FilePathField(path=None[, match=None, recursive=False, max_length=100, **options])   #varchar
V=models.SlugField([max_length=50, **options])              #varchar Tags, Incorporated Indexes 
V=models.CommaSeparatedIntegerField(max_length=None[, **options])              #varchar
V=models.IntegerField([**options])              #int
V=models.PositiveIntegerField([**options])              #int  Positive integer 
V=models.SmallIntegerField([**options])              #smallint
V=models.PositiveSmallIntegerField([**options])              #smallint  Positive integer 
V=models.AutoField(**options)              #int ; In Django Inside the code is self-increasing 
V=models.DecimalField(max_digits=None, decimal_places=None[, **options])              #decimal
V=models.FloatField([**options])              #real
V=models.BooleanField(**options)              #boolean Or bit
V=models.NullBooleanField([**options])              #bit Field can be set on null Value 
V=models.DateField([auto_now=False, auto_now_add=False, **options])              #date
#auto_now The date on which the record was last modified; auto_now_add Date the record was added 
V=models.DateTimeField([auto_now=False, auto_now_add=False, **options])              #datetime
V=models.TimeField([auto_now=False, auto_now_add=False, **options])              #time
V=models.TextField([**options])              #text
V=models.XMLField(schema_path=None[, **options])              #text
 ----------------------------- 
V=models.ForeignKey(othermodel[, **options])              # Foreign key, associate other models, create associated indexes 
V=models.ManyToManyField(othermodel[, **options])              # Many-to-many, associate other models, and create associated tables 
V=models.OneToOneField(othermodel[, parent_link=False, **options])              #1 Right 1 Field associated table properties 

Classic scenario example

The relationship among books, authors and publishers. For the convenience of demonstration, we try our best to simplify the fields in the table. The book table has book titles, and the publishing house establishes a one-to-many relationship with the publishing house table [foreign key]. A book can have multiple authors and establish a many-to-many relationship with the author table [many-to-many]. The author table has names and ages, and the publishing house table has publishing house names.


from django.db import models
class Publisher(models.Model):
  name = models.CharField(max_length=30)
 
  def __str__(self):
    return self.name
 
class Author(models.Model):
  name = models.CharField(max_length=30)
  age = models.IntegerField()
 
  def __str__(self):
    return self.name
 
class Book(models.Model):
  title = models.CharField(max_length=100)
  authors = models.ManyToManyField(Author)
  publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
 
  def __str__(self):
    return self.title

Select object

Get all objects


Publisher.objects.all() # Get all objects 

Filter objects


Publisher.objects.filter(name=' People's Education Press ') # Gets the 1 Object list 
dict = {'name':'lemon','age':18}
Author.objects.filter(**dict) # Method of transferring parameters from list 

Get a single object


Publisher.objects.get(name=' Machinery industry press ') # If you can't find it, you will report an error! ! ! 

Object sorting


Author.objects.order_by("name","-age") # You can sort by multiple fields, -  Represents reverse sorting 

Continuous investigation


Author.objects.filter(name='lemon').order_by('-age')[0]

Batch update


Author.objects.all().update(age='18')

Delete an object


Author.objects.filter(name='lemon').delete()

Foreign keys and many-to-many operations

Access foreign key


Book.objects.get(id=1).publisher # The publisher that got the book 

Reverse query


from django.db import models
class Publisher(models.Model):
  name = models.CharField(max_length=30)
 
  def __str__(self):
    return self.name
 
class Author(models.Model):
  name = models.CharField(max_length=30)
  age = models.IntegerField()
 
  def __str__(self):
    return self.name
 
class Book(models.Model):
  title = models.CharField(max_length=100)
  authors = models.ManyToManyField(Author)
  publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
 
  def __str__(self):
    return self.title
0

Many-to-many operation


from django.db import models
class Publisher(models.Model):
  name = models.CharField(max_length=30)
 
  def __str__(self):
    return self.name
 
class Author(models.Model):
  name = models.CharField(max_length=30)
  age = models.IntegerField()
 
  def __str__(self):
    return self.name
 
class Book(models.Model):
  title = models.CharField(max_length=100)
  authors = models.ManyToManyField(Author)
  publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
 
  def __str__(self):
    return self.title
1

Custom models method


from django.db import models
class Publisher(models.Model):
  name = models.CharField(max_length=30)
 
  def __str__(self):
    return self.name
 
class Author(models.Model):
  name = models.CharField(max_length=30)
  age = models.IntegerField()
 
  def __str__(self):
    return self.name
 
class Book(models.Model):
  title = models.CharField(max_length=100)
  authors = models.ManyToManyField(Author)
  publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
 
  def __str__(self):
    return self.title
2

Run results:

aa = models.Author.objects.get(id=1)
print(aa.status())
The results of the operation
Handsome boy

Custom manager Manager


class AuthorManager(models.Manager):
  def name_count(self,str_name):
    return self.filter(name__icontains=str_name).count()
class Author(models.Model):
  name = models.CharField(max_length=30)
  age = models.IntegerField()

  def __str__(self):
    return self.name
  def status(self):
    if self.name=='lemon':
      return ' Handsome boy '
  #1 Once a new manager is defined, the default manager needs to be displayed and declared before it can be used 
  objects = models.Manger() # Default Manager 
  object=AuthorManager() # New Definition Manager 

Implementation results:

aa = models.Author.object.name_count('lemon')
print (aa) #----"2

Custom sql statement


from django.db import models
class Publisher(models.Model):
  name = models.CharField(max_length=30)
 
  def __str__(self):
    return self.name
 
class Author(models.Model):
  name = models.CharField(max_length=30)
  age = models.IntegerField()
 
  def __str__(self):
    return self.name
 
class Book(models.Model):
  title = models.CharField(max_length=100)
  authors = models.ManyToManyField(Author)
  publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
 
  def __str__(self):
    return self.title
4

Implementation results:

aa = models.Author.object.age_stat(18)
print(aa)
-----------------
['lemon', 'Luouo']

Filter field sending method

__exact is exactly equal to like 'aaa'
__iexact is exactly equal to ignoring case ilike 'aaa'
__contains contains like '% aaa%'
__icontains contains ilike '% aaa%' that ignores case, but for sqlite, contains works as well as icontains.
__gt is greater than
__gte is greater than or equal to
__lt is less than
__lte is less than or equal to
__in exists within 1 list range
__startswith begins with...
__istartswith begins with... ignoring case
__endswith ends with...
__iendswith ends with..., ignoring case
__range is in the range of
Year of __year Date Field
Month for __month Date Field
Date of __day Date Field
__isnull=True/False


Related articles: