Here's the basics of Django's model.
models.py
from django.db import models
class SampleModel(models.Model):
# id = models.AutoField(primary_key=True)
char_sample = models.CharField(max_length=200)
char_with_null = models.CharField(max_length=10, blank=True, null=True)
char_options = models.CharField(choices=(('one', 1), ('two', 2)))
text_sample = models.TextField()
bool_sample = models.BooleanField(default=False)
datetime_created = models.DateTimeField(auto_now_add=True)
datetime_updated = models.DateTimeField(auto_now=True)
date_sample = models.DateField()
def __str__(self):
return self.char_sample
Primary key
The primary key is set automatically, even if you don't specify it.
In views etc., you can refer to it in the form of pk
etc.
CharField
A field for entering characters. HTML tags correspond to <input type =" text ">
.
max_length
(maximum number of characters) must always be specified.
Also, if blank = True
, blank is allowed at the time of validation, and if null = True
, null is allowed at the time of data registration.
blank =
and null =
can be used in other fields as well.
TextField
This is also a field for entering characters. The HTML tag corresponds to <textarea>
, and you can enter a large number of characters.
BooleanField
A field that accepts boolean values.
If default = False
is specified, it will be treated as False
if it is not specified at the time of data registration.
default =
can also be used in other fields.
DateTimeField
A field for entering the date and time.
If ʻauto_now_add = True, the date and time of that timing is registered only once at the beginning, and it is not updated after that. If ʻauto_now = True
, the date and time of registration timing will be updated automatically.
DateField
A field for entering a date.
The last __str__
function is written to refer to the specified field as the title instead of the primary key when referencing the model on the management screen.
admin.py
from django.contrib import admin
from .models import SampleModel
admin.site.register(SampleModel)
Add ʻadmin.site.register (model name)` to refer to the model on the management screen.
Here, we explained the model-related settings. Next time, I will explain about views.
Recommended Posts