How to use the Model in Django, djangomodel

Source: Internet
Author: User
Tags add time

How to use the Model in Django, djangomodel

Preface

This article mainly introduces the relevant content about the Model used in Django, and shares it for your reference and learning. I will not talk about it much below. Let's take a look at the detailed introduction.

Create model

When using the Django model, pay attention to the following two aspects: field type and method rewriting. Here we use an example to illustrate the common field types and how to override them.

From django. db import modelsclass School (models. model): passclass Message (models. model): passclass Teacher (models. model): pass class Student (models. model): GENDER_CHOICES = ('male', "Male'"), ('female ', "female"), ('secret', "confidential") name = models. charField (max_length = 40, blank = True, verbose_name = "name") gender = models. charField (max_length = 6, choices = GENDER_CHOICES, default = "secret", verbose_name = "gender") age = models. integerField (default = 0, verbose_name = "Age") rank = models. positiveIntegerField (default = 1, verbose_name = "rank", unique = True) discount = models. decimalField (max_digits = 3, decimal_places = 2, verbose_name = "", default = 1.0) school = models. foreignKey (to = School, verbose_name = "School", on_delete = models. CASCADE) message = models. oneToOneField (to = Message, verbose_name = "", on_delete = models. CASCADE) teacher = models. manyToManyField (verbose_name = "", to = Teacher, blank = True) introduce = models. textField (blank = True, verbose_name = "") grade = models. floatField (default = 0.0, verbose_name = "") url = models. URLField (verbose_name = "Personal Homepage", max_length = 100) email = models. emailField (verbose_name = "Mailbox") image = models. imageField (upload_to = 'img/% Y/% m/% d/', verbose_name = 'upload image', null = True) file = models. fileField (upload_to = "file/% Y/% m/% d/", verbose_name = "Upload file", blank = True) is_deleted = models. booleanField (verbose_name = "deleted", default = False, blank = True) time_added = models. dateTimeField (verbose_name = "add time", auto_now_add = True, blank = True) def delete (self, using = None, keep_parents = False): self. is_deleted = True # some actions self. save () def save (self, force_insert = False, force_update = False, using = None, update_fields = None): # some actions self. name = self. name. capitalize () # capital return super (). save (force_insert = force_insert, force_update = force_update, using = using, update_fields = update_fields) def _ repr _ (self): return "UserProfile :{}". format (self. name) def _ str _ (self): return self. name class Meta: ordering = ['-time_added'] verbose_name = "User Information" verbose_name_plural = verbose_name db_table = "student_info"

Field Type

Here, we will describe some important points in common fields.

CharField

It is worth noting that the choices parameter should be used to point to the preset value when the field can only be a specified value.

IntergerField & PositiveIntegerField

Integer and positive integer.

DecimalField

Decimal floating point number. The max_digits parameter indicates the number, and decimal_places indicates the number of digits in the decimal part.

ForeignKey

Use to point to the associated model, and use on_delete to specify the processing method of the object when the associated object is deleted. There are two main values: models. CASCADE and models. SET_NULL. Models. CASCADE indicates that this object is deleted when it is deleted, models. SET_NULL indicates that this object is set to null when the associated object is deleted, provided that this field is allowed to be null.

ImageField & FileField

Use the upload_to parameter to specify the file storage path. Note: the path set in MEDIA_ROOT is the actual storage path of the uploaded file. For example, the path of MEDIA_ROOT is '/home/media ', the Image Upload path is similar to/home/media/img/2018/03/06.

BooleanField

Boolean type. You can use default to specify the default value.

DateTimeField

In Django, there are three types of time fields: DateTimeField, DateField, and TimeField. The three types correspond to datetime (), date (), and time () respectively, and both have the auto_now and auto_now_add parameters.

  • Auto_now
    The default value is False. When it is set to True, the object is automatically updated to the current time each time it is modified, but the value of this field cannot be manually modified.
  • Auto_now_add
    The default value is False. When it is set to True, it is automatically set to the current time when the object is created, and it is not modified later, nor can it be manually modified.
  • Default current time, which can be modified
    Sometimes we need to set the field value to the current time when creating the object and modify it later. auto_now or auto_now_add cannot achieve this. In this case, you can use the default parameter to set the default value, as shown below:
From django. db import modelsfrom django. utils import timezoneclass Message (models. model): add_date = models. dateTimeField (verbose_name = 'Save date', default = timezone. now) mod_date = models. dateTimeField (verbose_name = 'last modified date', auto_now = True)

Rewrite Method

Delete

Django deletes data from the database by default. Sometimes we need to delete it to save the previous data. In this case, we can use a Boolean field to identify whether to delete the data, in this case, you need to override the delete method to implement soft deletion.

In the delete method, set is_deleted to True, indicating that the data has been deleted. In addition, you can perform some associated actions, such as assigning values to related fields, and finally save the object.

Save

Rewriting the save method allows us to perform some related operations when saving data. For example, the first letter is set to uppercase when saving the name. After the operation, we need to call the save method of the parent class to save the data.

Repr & str

The two functions are to convert variables or constants to string objects. Here, we rewrite this method to convert object instances to strings.

Class Meta

  • Ordering: how to sort the result set. The preceding example shows the reverse order of the added time.
  • Verbose_name: Object Name
  • Verbose_name_plural: name in the complex form of an object
  • Db_table: name of the table in the database

Common Methods

In the introduction to common methods section, because the model above contains many fields, the model created above is not used. Some common models are used here. The Representative content can be known by name, so the model is not listed.

Create an instance

Create

You can use the create method to create a model instance and set the values of each field in parameters.

student = Student.objects.create(name='zhangsan', gender='male')

Get_or_create

Get_or_create is used to query an instance. If the instance does not exist, an instance is created.

obj, created = Person.objects.get_or_create( first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)},)

The function returns a (object, created) tuple. The object is a query or created object instance, and the created is a Boolean value, indicating whether it is a newly created instance. When querying, use parameters other than ults. When the instance does not exist, it will contain the default parameter to create a new instance. The function is similar to the following code:

try: obj = Person.objects.get(first_name='John', last_name='Lennon')except Person.DoesNotExist: obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)) obj.save()

Update_or_create

Update_or_create is used to update an instance. An instance is created when the instance does not exist.

obj, created = Person.objects.update_or_create( first_name='John', last_name='Lennon', defaults={'first_name': 'Bob'},)

The function returns a (object, created) tuple. The object is an updated or created object instance, and the created is a Boolean value, indicating whether it is a newly created instance. When the queried object instance exists, use the parameter in default to update it. When the instance does not exist, create a new object instance and set the value of the field to be updated to the value in default. Similar functions:

defaults = {'first_name': 'Bob'}try: obj = Person.objects.get(first_name='John', last_name='Lennon') for key, value in defaults.items():  setattr(obj, key, value) obj.save()except Person.DoesNotExist: new_values = {'first_name': 'John', 'last_name': 'Lennon'} new_values.update(defaults) obj = Person(**new_values) obj.save()

Add

Here we will add the add method, which is used in the Multi-to-many relationship model to add the pointing object of this field.

>>> 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)

The Author above indicates the Author model, and the entry indicates the book entries. A book can have multiple authors and adopt many-to-many relationships. Add can add multiple authors to the book instance.

Query

All

The all method queries all instances of the object.

all_entries = Entry.objects.all()

Get

When you use get to query an instance, an exception is returned if the instance does not exist.

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

Filter

The filter returns a QuerySet instead of an object instance. If the query result does not exist, an empty QuerySet is returned, instead of returning a field. You can slice the result set to obtain the instance content. The following code is equivalent to the get operation on an object instance.

>>> entry = Entry.objects.filter(pk=1)[0]>>> cheese_blog = Blog.objects.filter(name="Cheddar Talk")[0]

The filter result can be operated in a chain, that is, multiple filter conditions can be followed.

Entry.objects.filter(pub_date__year=2006)Entry.objects.all().filter(pub_date__year=2006)Entry.objects.filter(blog__name__year="zhangsan")

The pub_date _ year above indicates the year in which the DateField type pub_date is retrieved. Similarly, the month _ month and day _ day can be retrieved. When using the foreign key ForeignKey, you can use double underscores to represent the fields of the associated object.

Now let's take a look at the example of chain filtering.

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

First, use _ startswith to filter data starting with 'wh. The data whose release date is earlier than today is retained. exclude indicates the data in the exclusion condition. The condition uses _ gte to indicate that the data is later than the current date, this part of filtering is similar to filtering followed by using less than _ lte. The last step is to use _ gte more than a custom date.

In addition to the preceding filter conditions, _ icontains is commonly used to include the content.

Q

Q is the built-in content of Django for query. The main purpose is to enter the content in the search box on the page to query the corresponding dataset in the background.

student = student.filter(Q(name__icontains=search) |       Q(teacher__name__icontains=search) |       Q(gender__icontains=search) |       Q(url__icontains=search))

In the preceding example, when a search box may search for the content of multiple fields, use "|" to calculate the content of each filter condition. When performing a multi-condition query, each condition is a parallel operation, and "&" is used instead of "| ".

Q can be copied to a variable. Sometimes we need to process the content after Q first, such as piecing the date together. In this case, Q can be assigned to a variable first, then, perform the "|" or "&" Operation on the variable.

query = Q(name__icontains=search)query = query | Q(teacher__name__icontains=search)student = student.filter(query)

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.