Showing results for models in django
Search instead for models em django
🌐
W3Schools
w3schools.com › django › django_models.php
Django Models
In Django, data is created in objects, called Models, and is actually tables in a database.
🌐
Django
docs.djangoproject.com › en › 6.0 › topics › db › models
Models | Django documentation | Django
A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.
Discussions

oop - Whats the difference between models and models.Model in django?(and similarly for forms and forms.Form ) - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I know that "models" is a module of package django.db, But why we inherit like class Foo(models.Model): while the all required fields like CharField, IntegerField, etc. More on stackoverflow.com
🌐 stackoverflow.com
python - what does " models.Model "mean - Stack Overflow
It means: make the Poll class inherit from the Model base class from the models module. ... Sign up to request clarification or add additional context in comments. ... It's a Django module, as you can see from from django.db import models 2013-02-05T19:39:32.807Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
ELI5: Django Models and Model Methods?
What kind of methods would be relevant? Whichever ones you need. I know that sounds like a smartass answer, but you can make them up as you need them. If you don't need any yet, then you don't need any. We can explore this idea in a bit. First, let's talk about some commonly-used builtin model methods. Built-in model methods In terms of default model methods that you can override, here are the ones I commonly use with Django templates (while also keeping in mind that you're using React): get_absolute_url(): Typically used to navigate to an object's DetailView e.g. after saving a form for that object. You probably don't need this in React. save(): Any time you save a model, you may want to do some custom stuff to it. You may need this. __str__(): When called, this model gives a string representation of that object. e.g. in templates, it will be displayed when you call {{ your_object }}, or when you call str(your_object) in your view code. You may need this. Custom methods In terms of custom methods, it depends on what you would want to do. For example, let's say you wanted to make comments threaded (maybe you don't need this, it's just an example). You could make a ForeignKey that ties a comment to another comment. Here's an example of how to do that. Add this field to your model: class Comment(models.Model): parent = models.ForeignKey('your_app.Comment', null=True, on_delete=models.SET_NULL) So we've created a ForeignKey named parent, which allows you to link a comment to another comment. It links to your model, is optional (null=True), and will not be deleted if its parent is deleted (on_delete determines what happens to an object if all its related objects are deleted. Use models.CASCADE if you want it to be deleted when its parent is deleted). OK, now that we have nested comments, I have an idea for a custom method: View most recent replies to that comment! Here's a method: def recent_replies(self): return self.comment_set.order_by('-timestamp')[:5] Now when we call your_object.recent_replies() in your view code, it will return up to 5 child comments, with the most recent ones displayed first. Hooray! Make sure to run manage.py makemigrations and manage.py migrate after modifying your fields. The ORM is the same for different databases. To answer the last question, yes. The field declarations are the same no matter what database is used. Note that there are some fields that are only used in PostgreSQL (see here ), but you probably don't need them (PostgreSQL is a good choice for a database though FYI). More on reddit.com
🌐 r/django
6
0
August 24, 2022
python - Django Model() vs Model.objects.create() - Stack Overflow
The django docs are a bit contradictory on this point in my opinion. I've had the same question and read "Note that instantiating a model in no way touches your database; for that, you need to save()." docs.djangoproject.com/en/1.10/ref/models/instances/… 2017-01-27T12:50:40.547Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › django-models
Django Models - GeeksforGeeks
The admin panel can now be used to create, update, and delete model instances. Django models consist of fields that define the structure of database tables.
Published   November 15, 2025
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn_web_development › Extensions › Server-side › Django › Models
Django Tutorial Part 3: Using models - Learn web development | MDN
Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc.
🌐
DjangoGirls
tutorial.djangogirls.org › en › django_models
Django models · HonKit
Post is the name of our model. We can give it a different name (but we must avoid special characters and whitespace). Always start a class name with an uppercase letter. models.Model means that the Post is a Django Model, so Django knows that it should be saved in the database.
🌐
Django
docs.djangoproject.com › en › 6.0 › topics › db
Models and databases | Django documentation | Django
A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-create-models-in-your-django-project
How to Create Models in Your Django Project
April 25, 2025 - If you're building something with Django, there's one thing you can't skip: creating models. Models are the heart of any Django app. They define how your data is structured, how it's stored in the database, and how Django can interact with it. Now, ...
🌐
TutorialsPoint
tutorialspoint.com › django › django_models.htm
Django - Models
A model is a class that represents table or collection in our DB, and where every attribute of the class is a field of the table or collection. Models are defined in the app/models.py (in our example: myapp/models.py) Following is a Dreamreal model
Find elsewhere
🌐
Medium
medium.com › @satyarepala › a-beginners-guide-to-django-models-understanding-each-option-with-clear-examples-27b85ba6935a
A Beginner’s Guide to Django Models: Understanding Each Option with Clear Examples | by Satya Repala | Medium
August 7, 2023 - Let’s delve into the most commonly used fields and explore examples for each: from django.db import models # CharField class Book(models.Model): # A field to store the title of the book (max length: 100 characters) title = models.CharField(max_length=100) # IntegerField class Student(models.Model): # A field to store…
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-create-django-models
How To Create Django Models | DigitalOcean
September 1, 2022 - It’s what Django uses to generate the database tables via their object relational mapping (ORM) API, referred to as “models.” · This tutorial is part of the Django Development series and is a continuation of that series. If you have not followed along with this series, we are making ...
🌐
MongoDB
mongodb.com › docs home › client libraries › python › django mongodb backend › model data
Create Models to Represent Collections - Django MongoDB Backend - MongoDB Docs
This sample models.py file defines a Movie model class that includes the following information: List of fields that represent movie data. Meta class that sets the db_table option to movies. This instructs Django MongoDB Backend to use this model to represent the sample_mflix.movies collection ...
🌐
Django Documentation
docs.djangoproject.com › en › 5.2 › ref › models › class
Model class reference | Django documentation | Django
Django ensures that in your model class you have at least a default Manager specified. If you don’t add your own Manager, Django will add an attribute objects containing default Manager instance. If you add your own Manager instance attribute, the default one does not appear.
🌐
Scaleway
scaleway.com › en › docs › tutorials › create-models-django
Creating models in your Django application | Scaleway Documentation
March 27, 2025 - To create your app, access the directory containing your manage.py file using a terminal, then run the following command: ... We create two models: Question and Choice. A Question has a question and a publication date.
🌐
GeeksforGeeks
geeksforgeeks.org › python › django-model-data-types-and-fields-list
Django Model Data Types and Fields List - GeeksforGeeks
Model fields define what kind of data a database column will store and how that data should be handled. Every field represents a specific data type and controls how data is stored and validated.
Published   November 14, 2025
🌐
freeCodeCamp
freecodecamp.org › news › common-django-model-fields-and-their-use-cases
Django Model Fields – Common Use Cases and How They Work
November 23, 2023 - A model field is a data type that stores a specific type of data. Each model field represents specific data, such as numbers, dates, texts, or even relationships with other models.
🌐
Reddit
reddit.com › r/django › eli5: django models and model methods?
r/django on Reddit: ELI5: Django Models and Model Methods?
August 24, 2022 -

My understanding so far is, the Django models is used to create the actual columns for the database.

Once I have declared the columns. What is the methods that follow it ? The documentation says this:

Define custom methods on a model to add custom “row-level” functionality to your objects. Whereas Manager methods are intended to do “table-wide” things, model methods should act on a particular model instance.

This is a valuable technique for keeping business logic in one place – the model.

ELI5?

I'm trying to create a comments section using React JS, this is the model I have so far:

class Comment(models.Model):

show = models.CharField(max_length=25)

username = models.CharField(max_length=16)

comment = models.TextField(max_length=1000)

time_stamp = models.DateTimeField()

What kind of methods would be relevant?

Also, I understand that Django comes default with sqlite3. If I was to go into settings.py and change the database to MySQL, would my models create the columns in MySQL instead? And would the backend admin page login take me to the MySQL database?

Top answer
1 of 4
4
What kind of methods would be relevant? Whichever ones you need. I know that sounds like a smartass answer, but you can make them up as you need them. If you don't need any yet, then you don't need any. We can explore this idea in a bit. First, let's talk about some commonly-used builtin model methods. Built-in model methods In terms of default model methods that you can override, here are the ones I commonly use with Django templates (while also keeping in mind that you're using React): get_absolute_url(): Typically used to navigate to an object's DetailView e.g. after saving a form for that object. You probably don't need this in React. save(): Any time you save a model, you may want to do some custom stuff to it. You may need this. __str__(): When called, this model gives a string representation of that object. e.g. in templates, it will be displayed when you call {{ your_object }}, or when you call str(your_object) in your view code. You may need this. Custom methods In terms of custom methods, it depends on what you would want to do. For example, let's say you wanted to make comments threaded (maybe you don't need this, it's just an example). You could make a ForeignKey that ties a comment to another comment. Here's an example of how to do that. Add this field to your model: class Comment(models.Model): parent = models.ForeignKey('your_app.Comment', null=True, on_delete=models.SET_NULL) So we've created a ForeignKey named parent, which allows you to link a comment to another comment. It links to your model, is optional (null=True), and will not be deleted if its parent is deleted (on_delete determines what happens to an object if all its related objects are deleted. Use models.CASCADE if you want it to be deleted when its parent is deleted). OK, now that we have nested comments, I have an idea for a custom method: View most recent replies to that comment! Here's a method: def recent_replies(self): return self.comment_set.order_by('-timestamp')[:5] Now when we call your_object.recent_replies() in your view code, it will return up to 5 child comments, with the most recent ones displayed first. Hooray! Make sure to run manage.py makemigrations and manage.py migrate after modifying your fields. The ORM is the same for different databases. To answer the last question, yes. The field declarations are the same no matter what database is used. Note that there are some fields that are only used in PostgreSQL (see here ), but you probably don't need them (PostgreSQL is a good choice for a database though FYI).
2 of 4
2
Defining custom methods depends if your application needs it . Even without custom methods simple CRUD will work just by using predefined methods. Try to work those predefined first till you get familiar, then if that doesn't satisfy what you need then create custom methods. https://docs.djangoproject.com/en/4.1/topics/db/queries/ Also, I understand that Django comes default with sqlite3. If I was to go into settings.py and change the database to MySQL, would my models create the columns in MySQL instead? And would the backend admin page login take me to the MySQL database? You need to run migrations first.then it will check what are the missing migrations on your new db and it will create those columns. Migrations only applies on the schema, that doesn't include the data from your old database. Based on your model. If its a comment section you need another field that represent the parent of a comment(post)
Top answer
1 of 6
382

https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects

To create and save an object in a single step, use the create() method.

2 of 6
75

The differences between Model() and Model.objects.create() are the following:


  1. INSERT vs UPDATE

    Model.save() does either INSERT or UPDATE of an object in a DB, while Model.objects.create() does only INSERT.

    Model.save() does

    • UPDATE If the object’s primary key attribute is set to a value that evaluates to True

    • INSERT If the object’s primary key attribute is not set or if the UPDATE didn’t update anything (e.g. if primary key is set to a value that doesn’t exist in the database).


  1. Existing primary key

    If primary key attribute is set to a value and such primary key already exists, then Model.save() performs UPDATE, but Model.objects.create() raises IntegrityError.

    Consider the following models.py:

    class Subject(models.Model):
       subject_id = models.PositiveIntegerField(primary_key=True, db_column='subject_id')
       name = models.CharField(max_length=255)
       max_marks = models.PositiveIntegerField()
    
    1. Insert/Update to db with Model.save()

      physics = Subject(subject_id=1, name='Physics', max_marks=100)
      physics.save()
      math = Subject(subject_id=1, name='Math', max_marks=50)  # Case of update
      math.save()
      

      Result:

      Subject.objects.all().values()
      <QuerySet [{'subject_id': 1, 'name': 'Math', 'max_marks': 50}]>
      
    2. Insert to db with Model.objects.create()

      Subject.objects.create(subject_id=1, name='Chemistry', max_marks=100)
      IntegrityError: UNIQUE constraint failed: m****t.subject_id
      

    Explanation: In the example, math.save() does an UPDATE (changes name from Physics to Math, and max_marks from 100 to 50), because subject_id is a primary key and subject_id=1 already exists in the DB. But Subject.objects.create() raises IntegrityError, because, again the primary key subject_id with the value 1 already exists.


  1. Forced insert

    Model.save() can be made to behave as Model.objects.create() by using force_insert=True parameter: Model.save(force_insert=True).


  1. Return value

    Model.save() return None where Model.objects.create() return model instance i.e. package_name.models.Model


Conclusion: Model.objects.create() does model initialization and performs save() with force_insert=True.

Excerpt from the source code of Model.objects.create()

def create(self, **kwargs):
    """
    Create a new object with the given kwargs, saving it to the database
    and returning the created object.
    """
    obj = self.model(**kwargs)
    self._for_write = True
    obj.save(force_insert=True, using=self.db)
    return obj

For more details follow the links:

  1. https://docs.djangoproject.com/en/stable/ref/models/querysets/#create

  2. https://github.com/django/django/blob/2d8dcba03aae200aaa103ec1e69f0a0038ec2f85/django/db/models/query.py#L440