- Django RESTful Web Services
- Gaston C. Hillar
- 271字
- 2021-06-30 19:30:57
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.
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.
- 企業級Java EE架構設計精深實踐
- 深度學習經典案例解析:基于MATLAB
- 單片機C語言程序設計實訓100例:基于STC8051+Proteus仿真與實戰
- ASP.NET Core Essentials
- Raspberry Pi for Secret Agents(Third Edition)
- Essential Angular
- Learning Apache Kafka(Second Edition)
- Unity 5.x By Example
- C語言程序設計上機指導與習題解答(第2版)
- 速學Python:程序設計從入門到進階
- Android移動開發案例教程:基于Android Studio開發環境
- 愛上C語言:C KISS
- Python程序設計教程
- Python趣味創意編程
- Three.js Essentials