Questions tagged [django-models]

For questions concerning use of the model class from the web framework Django.

The centerpiece of the Django object-relational mapping scheme is the Model. 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, in a way that is mostly decoupled from the vendor-specific implementation details of the chosen database.

The basics:

  • Each model is a Python class that subclasses django.db.models.Model.
  • Instances of models correspond to table rows.
  • Models contain field attributes, which correspond to table columns.
  • Model methods correspond to SQL queries and procedures on those queries.
  • Arguments to model fields and attributes of inner Meta classes correspond to DDL properties on the underlying database tables.

Django imbues models with an automatically-generated database-access API, which in most cases allows data to be accessed and modified in a Pythonic paradigm, as opposed to writing raw SQL.

Altering the format of your models (that is, changing the fields of your models, or adding new models, as opposed to adding or altering model instances) is known as schema migration.

In addition to defining the relational schema of your data, standard practice for coding Django applications is to include the business logic for queries and actions on your model entities within your model classes (for instance- or row-level operations) and in associated Managers (for class- or table-level operations).

Some examples

There is a "dumb" sort of way to retrieve data from a database in a view. It’s simple: just use any existing Python library to execute an SQL query and do something with the results.

This is achieved by using the MySQLdb to connect to a MySQL database, retrieve some records, and feed them to a template for display as a Web page:

from django.shortcuts import render
import MySQLdb

def book_list(request):
    db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost')
    cursor = db.cursor()
    cursor.execute('SELECT name FROM books ORDER BY name')
    names = [row[0] for row in cursor.fetchall()]
    db.close()
    return render(request, 'book_list.html', {'names': names})

This approach works, but some problems should jump out at you immediately:

  • We’re hard-coding the database connection parameters. Ideally, these parameters would be stored in the Django configuration.
  • We’re having to write a fair bit of boilerplate code: creating a connection, creating a cursor, executing a statement, and closing the connection. Ideally, all we’d have to do is specify which results we wanted.
  • It ties us to MySQL. If, down the road, we switch from MySQL to PostgreSQL, we’ll have to use a different database adapter (e.g., psycopg rather than MySQLdb), alter the connection parameters, and – depending on the nature of the SQL statement – possibly rewrite the SQL. Ideally, the database server we’re using would be abstracted, so that a database server change could be made in a single place. (This feature is particularly relevant if you’re building an open-source Django application that you want to be used by as many people as possible.)

As you might expect, Django’s database layer aims to solve these problems. Here’s a sneak preview of how the previous view can be rewritten using Django’s database API:

from django.shortcuts import render
from mysite.books.models import Book

def book_list(request):
    books = Book.objects.order_by('name')
    return render(request, 'book_list.html', {'books': books})

References:

43372 questions
10
votes
3 answers

How to fix: TypeError: QuerySet.annotate() received non-expression(s): eqmunir

I am adding a like functionality in my website where users can like each others posts. I have done this successfully, however have one issue. This is checking whether the user has already liked the post, which has to be performed specifically in my…
djangoninja
  • 143
  • 1
  • 1
  • 7
10
votes
2 answers

Difference between UniqueConstraint vs unique_together - Django 2.2?

I started the new project in Django using version 2.2,which has new constraint unique constraint, Does this same as unique_together or it has any other differences?
Hari
  • 1,545
  • 1
  • 22
  • 45
10
votes
7 answers

How do I create a custom UserChangeForm that does not allow certain fields to be edited?

This is my second post on SO, as well as my second post on Django--please be gentle. I am working on a simple User model. Users should be able to sign up for the site, and after signing up they should be able to change their account settings upon…
Brian Gesiak
  • 6,648
  • 4
  • 35
  • 50
10
votes
2 answers

Django getter on model field

I'm using Django 2.x I have a model like class MyModel(models.Model): name = models.CharField() balance = models.IntegerField() I want to change the value of balance on the GET request without changing the value in the database. Like if it…
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285
10
votes
1 answer

Accessing model instance from validator

How would I access the instance of the model that is being validated from within the validator for a specific field? models.py def question_instances(value): #validator # not sure how to get model instance within this function industry…
Jason Howard
  • 1,464
  • 1
  • 14
  • 43
10
votes
4 answers

redirect vs reverse django

I have experienced using reverse within get_absolute_url method in the model, but I wish I have an idea about the difference between reverse and redirect, I have tried to search on google about it but there is almost nothing I don't know what should…
10
votes
2 answers

Implementation of e-mail verification in Django

I have created a Django app. I have a registration page(simple HTML form) in the app,and it has an e-mail field while registering. Now i wanted to implement an email verification when the user registers. Like sending an email to the user (to email…
rv_k
  • 2,383
  • 7
  • 39
  • 52
10
votes
2 answers

Django Two Factor Authentication

I have recently been reading through the documentation about django-two-factor-authentication which I found here : https://django-two-factor-auth.readthedocs.io/en/stable/installation.html The documentation is great. However, I'm trying to…
10
votes
7 answers

What's the standard way of saving something only if its foreign key exists?

I'm using Python 3.7 and Django . I have the following model, with a foreign key to another model ... class ArticleStat(models.Model): objects = ArticleStatManager() article = models.ForeignKey(Article, on_delete=models.CASCADE,…
Dave
  • 15,639
  • 133
  • 442
  • 830
10
votes
4 answers

django.db.utils.IntegrityError: FOREIGN KEY constraint failed

My models.py class Order(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.PROTECT) customer_email = models.EmailField(blank=True, null=True, default=None) customer_name = models.CharField(max_length =…
Nikita Shuliak
  • 119
  • 1
  • 1
  • 11
10
votes
4 answers

Django: Why create a OneToOne to UserProfile instead of subclassing auth.User?

Note: If you are tempted to 'answer' this question by telling me that you don't like django.contrib.auth, please move on. That will not be helpful. I am well aware of the range and strength of opinions on this matter. Now, the question: The…
10
votes
2 answers

django model foreign key queryset selecting related fields

I am trying to select from the join of the two related tables in DJango as shown below. But I am not able get the field name of the other table. In SQL we can write: select person.phonenumber,membership.* from membership where person=name ; This…
sush
  • 5,897
  • 5
  • 30
  • 39
10
votes
1 answer

TypeError: __init__() got an unexpected keyword argument 'on_delete'

I built a model: class Channel(models.Model): title = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') description_html =…
Majid Rajabi
  • 1,417
  • 6
  • 20
  • 35
10
votes
1 answer

Forbid updating a django model field

I have the following model: class Project(models.Model): name = models.CharField(max_length=200) class Task(models.Model): name = models.CharField(max_length=200) project = models.ForeignKey('Project', on_delete=models.CASCADE, …
seblat
  • 141
  • 1
  • 4
10
votes
1 answer

How to capture the Model.DoesNotExist exception in Django rest framework?

In Django REST Framework, when you query a database model and it does not exist an exception will be raised as ModelName.DoesNotExist. This exception will change according to the model name. For example: Querying the Car model will raise…
Kramer Li
  • 2,284
  • 5
  • 27
  • 55