models.py---The Database model in Django

Source: Internet
Author: User
Tags serialization sorted by name

Django makes database queries and management through the creation of models. The models.py file in the Django app directory is used to save the data model, where each class can correspond to a table in the database, and the interface of the query is very simple and efficient.

First of all, the configuration of the database is still implemented in settings.py, you can refer to the previous article http://blog.csdn.net/icetime17/article/details/42506779. Configured as follows

# database Settings databases = {'    default ': {        ' ENGINE ': ' Django.db.backends.mysql ',        ' NAME ': ' mydb1 ',        ' USER ': ' mydb1 ', '        PASSWORD ': ' 123456 ',        ' HOST ': ' 192.168.5.126 ',        ' PORT ': 3306,        ' OPTIONS ': {              ' CharSet ': ' UTF8 ',              ' use_unicode ': True,        },    },}
Next, let's look at how to use the Python MySQLdb class library to query the database.

Import mysqldbdb = MySQLdb.connect (host= ' 192.168.5.126 ', db= ' mydb1 ', user= ' mydb1 ', passwd= ' 123456 ') cursor = Db.cursor ( query = ' SELECT * from Result_result ' cursor.execute (query) # get Query data = Cursor.fetchall () print data[0]names = [Row[0] fo R row in Data]db.close ()
As for MySQLdb's detailed API, we can check their official website, here will not repeat.

So, the play is coming, let's just throw away the mysqldb and look at the data model that Django comes with.

1. Building a data Model

A preliminary models.py file is as follows:

From django.db import models# Create your models Here.class Result (models. Model):    #每一条对应数据库一个table中的一列      name = models. Charfield (max_length=20)    addr = models. Charfield (max_length=100) Time    = models. Datetimefield ()    content = models. Charfield (max_length=10000)    tid = models. Integerfield (default=0)    status = models. Integerfield (default=0)        website = models. Urlfield ()    # Adds a string representation of the model.    def __str__ (self):        return '%s '% (Self.name, self.address)    # meta is an inner class that holds the metadata used to describe the model.    Class Meta:        # If order_by is not provided, it is sorted by name by default.        ordering = [' name ']
In the models.py file, each class is a subclass of Django.db.models.Model, corresponding to a table in the database, and each property in the class result corresponds to each column record in the table.

Then execute Python manage.py sqlall result to create or view all the table under the Django APP result. If you create a new table, you will be given the SQL Statement's table-building hints.

(Django will only create a new table without modifying the existing table.)

Without errors, it means that the model is available. Then execute the python manage.py syncdb execute these SQL statements, and the table of the database is already established.

2, query operation

Django provides a very handy database query interface that executes the Python manage.py shell into the Django Shell interface:

From django.db import modelsfrom result.models Import resultdata = {    ' name ': ' Chris ',    ' addr ': ' Address ',    ' Time ': ' 2015-1-3 19:30:00 ',    ' content ': ' Haha, come again. ', '    website ': ' http://www.github.com/icetime17 ',}r = Result ( name=data[' name '], addr=data[' addr '], time=data[' time ',    <span style= ' White-space:pre ' ></span> content=data[' content '], website=data[' website ']) R.save () # or use R.save (using= ' Result_result ') to set the table name
The object that creates a result directly, that is, a new record is created. Use Save () to store it in DB, which completes the write of a record.

Some of the main query operations are as follows:

# select * from Result_result; Result.objects.all () # Extract the First 100 Records Result.objects.all () [0:100]# where Name= ' Chris ' and addr= ' address ' Result. Objects.filter (name= ' Chris ', addr= ' address ') # where name like '%chris% ' Result.objects.filter (name_contains= ' Chris ') # Get a record Result.objects.get (name= ' Chris_unique ') # Delete a record Result.objects.get (name= ' Chris_unique '). Delete () # Delete multiple data Result.objects.filter (name= ' Chris '). Delete () # Order by nameResult.objects.order_by (' name ') # Reverse sort Result.objects.filter (name= ' Chris '). Order_by ('-name ') # Modify AddrResult.objects.filter (name= ' Chris '). Update ( Addr= ' address_updated ') # Extract the specific contents of the Data R = Result.objects.get (name= ' chris_unique ') print R.name, r.addr
Above, just simply record some of the basic operations. For more detailed information, please refer to http://djangobook.py3k.cn/chapter05/.

3, serialization of Modelserializer

The Django Rest Framework Framework provides serialization encapsulation operations on the Django data model. Serialization is similar to encapsulating all of the value operations on Resut objects.

First, the serializers.py file is introduced, and the individual columns of the result object are associated with the subclasses of the Rest_framework.serializers.ModelSerializer, in the manner of the code below.

# serializers.pyfrom rest_framework Import serializersfrom result.models import ResultClass Resultserializer ( serializers. Modelserializer):    class Meta:        model = Result Fields        = (' name ', ' addr ', ' time ',            ' content ', ' tid ', ' Status ', ' website ')
This makes it easier to manipulate the result object in the following way:

Import jsonfrom django.http import httpresponsefrom rest_framework.renderers import Jsonrendererfrom result.models        Import resultfrom result.serializers Import resultserializerdef QueryResults (Request): if Request.method = = ' GET ': If Request.session.has_key ("userid"): Data = Resultserializer (Result.objects.filter (name=req uest.session[' userid ']) [0:10], many=true). Data data = Jsonrenderer (). Render (data) return httprespons E (Json.dumps ({"Status": 0, "Data": Data}), content_type= "Application/json") Else:ret                    Urn HttpResponse (json.dumps ({"Status": 1, "err_msg": "Can not find the user info"}), Content_type= "Application/json") Else:return HttpResponse (Json.dumps ({"Status": 1, "err_msg": " It only support HTTP GET method. "}), content_type=" Application/json ")
This QueryResults method receives a GET request, queries the user's records according to the UserID in session, and forms the data back in JSON format.
With Resultserializer, and its various fields (field) correspond to the columns of the result object. The method that queries the result object can be encapsulated as follows:

data = Resultserializer (Result.objects.filter (name=request.session[' userid ')) [0:10], many=true). Data

The generated data is actually an array of query results, converted to JSON format by the following way
data = Jsonrenderer (). Render (data)

About the serialized content, here is just about to mention, there are more useful operations, we can refer to http://www.django-rest-framework.org/tutorial/1-serialization/.


Well, for the Django data model, it's here for the time being. Welcome to discuss together.





models.py---The Database model 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.