Define a Simple Django Model
A snippet showing how to define a simple Django model with CharField and DateTimeField.
# models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
# Django Shell
# python manage.py shell
>>> from blog.models import Post
>>> Post.objects.create(title='First Post', content='This is a test.')
>>> Post.objects.all()
Explanation:
-
This model defines a
PostwithCharField,TextField, andDateTimeField. -
auto_now_add=Trueautomatically sets the timestamp when the object is created. -
The
__str__method controls how the object is displayed (e.g. in Django admin). - You can create and view model data using the Django shell or admin.
- Category Models & ORM
- Total Views 658
- Last Modified 13 September, 2025
- Tags #models #orm #fields #basics
Previous snippet
Social Login with django-allauth
Next snippet