ORM Advanced operations in Django

Source: Internet
Author: User

ORM Advanced operations in Django

Django is the use of ORM to operate the database, through the ORM can be very easy to achieve the interaction with the database. However, there are still several operations that are very round and particularly confusing. So, for this piece, to a classification summary it.

For the ORM to the basic operation of the database has already been introduced in the previous model, here specifically for the ORM's one-to-many, many-to-many, forward, reverse and other operations to explain the usage and considerations.

Two in mind:

    • Double underline "__" When searching for data in a table operation filter
    • Use the point "." When fetching data .

One or one-to-many

Start by designing two simple tables and setting a foreign key value for another table in one of the tables

#--*--Coding:utf-8-*-from django.db import Modelsclass usertype (models. Model):    caption = models. Charfield (MAX_LENGTH=32) class UserInfo (models. Model):    User_type = models.  ForeignKey(usertype)    username = models. Charfield (max_length=32) Age    = models. Integerfield ()


1. Add Data:

The way to pass the ID : (Dictionary of the form of the parameter)

User_dict = {"username": "Chenchao", "Age": "+", "User_type_id": 1}models. UserType.objects.create (**user_dict)

How to pass objects :

User_type_obj = models. UserType.objects.get (id=1)   #先获取外键表中的数据对象user_dict = {"username": "Chenchao", "Age": "+", "User_type": User_type_ obj}        #将对象传入字典models. UserType.objects.create (**user_dict)

Explanation: when we write the models class, the Foreign key field is "User_type", and Django saves the field in the database by default with "_id", so you can pass the ID directly.

the Foreign key field "User_type" in the table also represents a row of data objects in the dictionary table. The same can be used to pass the object of the way to the argument.

2. Delete data

3. Modify the data (these two operations are basically the same as the Add usage above)

4. Find Data

Forward Lookup : (The lookup is positive based on the presence of a foreign key value table )

Models. UserInfo.objects.filter (user_type__caption"CEO")   # double underline "__"

  Reverse Lookup : (based on a lookup that does not have a foreign key value table as a reverse lookup, provided the two tables have established a relationship )

  • The Foreign key table we created has two fields, ID, caption. But the Django default foreign key table also buries a field userinfo. You can get a value that does not exist in a table, and you can see it by returning an error in the Yellow pages.
  • The values obtained through models are qureyset. As long as this type is available, you can use the. Filter. Count method
  • We know that User_type_obj gets a row of data objects in the foreign key table.
      • User_type_obj.id represents a data
      • User_type_obj.caption represents a data
      • User_type_obj. Userinfo_set is special and represents a kind of ability. This ability is available to all users under this user type or to a few users
      • Request.user The surrogate refers to a row of data from the auth table that Django comes with, and UserInfo makes a onetoone that is the same as a forward query. So you can also use request.user.userinfo.filter ....

Example: Get what type of user is a person? How many people are there under the current user type?

" Chenchao " )  #通过外键表来找到隐藏的userinfo字段下的usernameuser_type_obj. Caption  #  get user Chenchao user type User_type_obj.userinfo_setAll (). Count ()  # Gets the number of users under this type

Examples of Likes:

First, design the database table structure, so that a list of likes and users and articles to establish a foreign key relationship

classMyUser (models. Model): Username= Models. Charfield (max_length=32) Password= Models. Charfield (max_length=64)    def __unicode__(self):returnSelf.usernameclassNews (models. Model): Title= Models. Charfield (max_length=32) Content= Models. Charfield (max_length=32)    def __unicode__(self):returnSelf.titleclassFavor (models. Model): User_obj=models. ForeignKey (MyUser) new_obj=models. ForeignKey (News)def __unicode__(self):return " %s,%s"% (Self.user_obj.username, self.new_obj.title)
View Code

ORM advanced operations in Django

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.