[django] - CRUD operation of models


Increase Create

1. preservation

To create an object, use the keyword parameter of the model class to instantiate it, then call save() to save it to the database.

#Method 1: the Test module usually creates and saves objects in one step
models.Entity.objects.create(c1='xx', c2='oo')   # Add a piece of data to accept dictionary type data * * kwargs

#Mode two 
obj = models.Entity(c1='xx', c2='oo')

The save() method does not return a value. If the model has an AutoField auto increment primary key, the auto increment value is evaluated and saved as an attribute on the object the first time you call it.

2. Save ForeignKey and ManyToManyField fields

An example of blog function:

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline

The working principle of updating ForeignKey field is exactly the same as that of saving common field. Only the object of correct type needs to be assigned to relevant field. This example updates the blog's property Entry, assuming that the appropriate instance Entry and blog have been saved to the database.

from blog.models import Blog, Entry

entry = Entry.objects.get(pk=1)
cheese_blog = Blog.objects.get(name="Cheddar Talk")
entry.blog = cheese_blog

The way ManyToManyField's work is updated is slightly different - use the method on the add() field to add records to the relationship. This example adds the Author instance to the entry object:

from blog.models import Author

joe = Author.objects.create(name="Joe")

To add more than one record at a time for ManyToManyField, include multiple parameters add() in the call to as follows:

john = Author.objects.create(name="John")
paul = Author.objects.create(name="Paul")
george = Author.objects.create(name="George")
ringo = Author.objects.create(name="Ringo")
entry.authors.add(john, paul, george, ringo)

3. Save the specified field

save() passes the field name list update fields in the keyword arguments, then only the fields named in the list are updated.

product.name = 'Name changed again'

Check Retrieve

1. Query all objects

all_entries = Entry.objects.all()

The QuerySet returned by the all() method contains all the objects in the database.

2. Use filter to query specific objects


Returns the QuerySet containing new objects that match the given lookup parameters.


Returns a new QuerySet containing objects that do not match the given lookup parameters.



Link filter

...     headline__startswith='What'
... ).exclude(
...     pub_date__gte=datetime.date.today()
... ).filter(
...     pub_date__gte=datetime.date(2005, 1, 30)
... )

The filtered QuerySets are unique

Each filter creates a separate, unique QuerySet that can be stored, used, and reused.

q1 = Entry.objects.filter(headline__startswith="What")
q2 = q1.exclude(pub_date__gte=datetime.date.today())
q3 = q1.filter(pub_date__gte=datetime.date.today())

The three QuerySets are separate. The first is that the QuerySet contains the basis for all entries, which contain titles that begin with "What.". The second is a subset of the first with additional conditions that do not include the records of pub date today or in the future. The third is a subset of the first with an additional condition that only pub date records of today or in the future are selected. The initial QuerySet (q1) is not affected by the optimization process.

3. Query a single object

If you know that only one object matches your query, you can use get() on Manger to return that object directly.

one_entry = Entry.objects.get(pk=1)

If there is no result matching the query, get() throws a DoesNotExist exception. In the above code, Django raises Entry.DoesNotExist if there is no object with Entry primary key 1.

Similarly, if more than one item matches the get() query, it raises multipleobjectsreturn.

Return to specified field

values() takes the optional location parameter * fields, which specifies which fields should be restricted by SELECT. If you specify fields, each dictionary will contain only the key / value of the specified field. If no fields are specified, each dictionary will contain keys and values for all fields in the database table.

# This list contains a Blog object.
>>> Blog.objects.filter(name__startswith='Beatles')
[<Blog: Beatles Blog>]

# This list contains a dictionary.
>>> Blog.objects.filter(name__startswith='Beatles').values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]

>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]

4. Magic double underscores of advanced query

·Greater than, less than

Entry.objects.filter(id__gt=1)               # Get a value with id greater than 1
Entry.objects.filter(id__gte=1)              # Get a value with id greater than or equal to 1
Entry.objects.filter(id__lt=10)              # Get a value with id less than 10
Entry.objects.filter(id__lte=10)             # Get a value with id less than 10
Entry.objects.filter(id__lt=10, id__gt=1)    # Get a value with id greater than 1 and less than 10

#SELECT * FROM app_entry WHERE id <= 10;

·Member judgment in

Entry.objects.filter(id__in=[11, 22, 33])   # Get data with id equal to 11, 22, 33
Entry.objects.exclude(id__in=[11, 22, 33])  # not in

##SELECT * FROM app_entry WHERE id in (11,22,33);

·Fuzzy contains

Entry.objects.filter(name__icontains="ven") # icontains case insensitive

#SELECT ... WHERE name LIKE '%ven%';

·Other matches

startswith,istartswith, endswith, iendswith,


Entry.objects.filter(id__range=[1, 2])   # Range between and

·order by

Entry.objects.filter(name='seven').order_by('id')    # asc
Entry.objects.filter(name='seven').order_by('-id')   # desc

·group by


# SELECT app_tb.id", COUNT(app_tb.num) AS c FROM app_tb WHERE app_tb.c1 = 1 GROUP BY app_tb.id

· limit ,offset

#Return to the first 5 objects (): LIMIT 5

#Returns the sixth to tenth objects (): OFFSET 5 LIMIT 5

To retrieve a single object instead of a list, use a simple index instead of a slice. For example, after sorting items alphabetically by title, this returns the first one in the database: SELECT foo FROM bar LIMIT 1


This is roughly equivalent to:




·Empty or not


·Time year / month / day / week_day / hour / minute / second / gt: year / month / day / week / hour / minute / second/

Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))

Delete Delete

Delete individual data


Delete data for specified conditions


Delete all data


Change Update

You can use either the save method or the update method. The difference is that the save method can not only update the existing object data in the data, but also create new objects. The update method can only be used to update existing object data. Generally speaking, if you want to update multiple object data at the same time, the update method is more appropriate.

Update with save method

obj = Entry.objects.get(id=1)
obj.name = '111'

Update with update method

obj = Entry.objects.get(id=1).update(name='new title')

Using update method to update multiple data


Common operation

<1> All(): query all results

<2> Get (* * kwargs): returns the object matching the given filter criteria. Only one result is returned. If more than one object meets the filter criteria or does not meet the filter criteria, an error will be thrown.
<3> Filter (* * kwargs): it contains objects that match the given filter criteria
<4> Exclude (* * kwargs): it contains objects that do not match the given filter criteria
<5> Values (* field): returns a ValueQuerySet -- a special QuerySet, which is not a series of model instantiated objects,

It's an iterative dictionary sequence
<6> Values_list (* field): it is very similar to values(), which returns a tuple sequence and values returns a dictionary sequence
<7> Order_by (* field): sort query results
<8> Reverse(): reverse sort query results, please note that reverse() can only be called on QuerySet with defined order (in Meta of model class

The order by () method is specified in.
<9> Distinct(): remove duplicate records from the returned results (if you query across multiple tables, you may get duplicate results when calculating the QuerySet). At this time, you can

Use distinct(), note that only PostgreSQL supports de duplication by field. )
<10> Count(): returns the number of objects in the database that match the query (QuerySet).
<11> First(): returns the first record
<12> Last(): returns the last record
<13> Exists(): returns True if the QuerySet contains data, False otherwise

32 original articles published, 15 praised, 10000 visitors+
Private letter follow

Tags: Database less Django Attribute

Posted on Mon, 10 Feb 2020 23:41:13 -0800 by jamessw