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 Post with CharField, TextField, and DateTimeField.
  • auto_now_add=True automatically 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
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.