Models in Django are the only true source of information about your data. They contain the essential fields and behaviors of the data you are storing. Generally, each model in Django maps to a single database table.
Templates are a crucial part when it comes to development with Django. They act as the middle layer between the database and the views. They are used to structure and manipulate the data in your database.
To create a model in Django, you need to define a class that inherits from django.db.models.Model. Each class attribute represents a database field. Django will then create a table for that model in the database with columns corresponding to the model's attributes.
For example, if you are building a blog system, you might have a Post template like this:
class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() pub_date = models.DateTimeField('date published')
In this example, the Post template has three fields - title, content and pub_date. Title is a character field with a maximum length of 200, content is a text field, and pub_date is a datetime field.
Django supports all common types of database fields - text fields, datetime fields, integer fields, decimal number fields, boolean fields, etc. In addition, Django also supports relationship fields like ForeignKey, ManyToManyField, and OneToOneField.
Once you've defined your models, Django provides a powerful and intuitive database API for interacting with your data. You can create, retrieve, update and delete records using this API. In addition, Django also provides an auto-generated administrative interface that allows you to interact with your data.
For example, to create a new Post, you can do the following:
post = Post(title='My first post', content='This is my first post', pub_date=datetime.now()) post.save()
To retrieve all Posts, you can do the following:
posts = Post.objects.all()
To update a Post, you can do the following:
post = Post.objects.get(id=1) post.title = 'My updated post' post.save()
To delete a Post, you can do the following:
post = Post.objects.get(id=1) post.delete()
In addition, Django's database API supports complex queries such as join queries, aggregation queries, etc.
In short, models in Django are a powerful and flexible way to work with your data. They provide a layer of abstraction over the database, allowing you to focus on business logic rather than database implementation details.