官术网_书友最值得收藏!

Creating our first model

Now, we will create a simple Toy model in Django, which we will use to represent and persist toys. Open the toys/models.py file. The following lines show the initial code for this file with just one import statement and a comment that indicates we should create the models:

from django.db import models 
 
# Create your models here. 

The following lines show the new code that creates a Toy class, specifically, a Toy model in the toys/models.py file. The code file for the sample is included in the hillar_django_restful_02_01 folder in the restful01/toys/models.py file:

from django.db import models 
 
 
class Toy(models.Model): 
    created = models.DateTimeField(auto_now_add=True) 
    name = models.CharField(max_length=150, blank=False, default='') 
    description = models.CharField(max_length=250, blank=True, default='') 
    toy_category = models.CharField(max_length=200, blank=False, default='') 
    release_date = models.DateTimeField() 
    was_included_in_home = models.BooleanField(default=False) 
 
    class Meta: 
        ordering = ('name',)

The Toy class is a subclass of the django.db.models.Model class and defines the following attributes: created, name, description, toy_category, release_date, and was_included_in_home. Each of these attributes represents a database column or field.

Django automatically adds an auto-increment integer primary key column named id when it creates the database table related to the model. It is very important to notice that the model maps the underlying id column in an attribute named pk for the model.

We specified the field types, maximum lengths, and defaults for many attributes. The class declares a Meta inner class that declares an ordering attribute and sets its value to a tuple of string whose first value is the 'name' string. This way, the inner class indicates to Django that, by default, we want the results ordered by the name attribute in ascending order.

主站蜘蛛池模板: 甘谷县| 安阳市| 曲水县| 青河县| 松江区| 汉寿县| 拉萨市| 蓝田县| 屯门区| 开平市| 星子县| 安溪县| 德兴市| 广饶县| 新巴尔虎左旗| 德江县| 阳江市| 平舆县| 安泽县| 科技| 南岸区| 阿拉善左旗| 萨嘎县| 灵璧县| 昌邑市| 安康市| 隆回县| 定襄县| 神农架林区| 桦南县| 梁平县| 塘沽区| 凤阳县| 潼南县| 察雅县| 土默特右旗| 霍邱县| 吉水县| 民权县| 新和县| 余干县|