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
2 answers

How to access model's class level variable in data migration?

Here is my model. Poll(models.Model): title = models.CharField(max_length=1024) MY_VAR = ['my_class_level_attribute'] # I want to access this Here is my data migration: def my_func(apps, schema_editor): Poll = apps.get_model('my_app',…
davidhwang
  • 1,343
  • 1
  • 12
  • 19
10
votes
1 answer

Can I make at least one field a requirement on a Django Model?

Say I have a Person model: class Person(models.Model): name = models.CharField(max_length=50) email = models.EmailField() telephone = models.CharField(max_length=50) For every Person I want to ensure that there is contact information.…
Oli
  • 235,628
  • 64
  • 220
  • 299
10
votes
2 answers

Find which fields are different between two instances of the same Model

Well, I think the question explains itself. I have two instances of a Django Model and I would like to know which fields differ. How could you do this in a smart way? Cheers!
gabn88
  • 781
  • 8
  • 23
10
votes
8 answers

"django.db.utils.ProgrammingError: relation "app_user" does not exist" during manage.py test

My setup: Django 1.8.3 Python 2.7.10 Ubuntu 14.04 django-two-factor-auth==1.2.0 I get the following error when I run python manage.py test: Traceback (most recent call last): File "/src/venv/bin/django-admin.py", line 5, in
Paul
  • 1,192
  • 1
  • 11
  • 23
10
votes
5 answers

Django Migration: Can't create table errno: 150

I have a brand new MariaDB serve (version: 5.5.41-MariaDB) and created a new database for my Django (1.8.2) application. The database was created using innoDB by default. I have a model that looks like this: class UserProfile(models.Model): …
CraigH
  • 2,041
  • 3
  • 30
  • 48
10
votes
4 answers

Django model subclassing: Get the subclass by querying the superclass

The following code is given: class BaseMedium(models.Model): title = models.CharField(max_length=40) slug = models.SlugField() class A(BaseMedium): url = models.URLField() class B(BaseMedium): email = models.EmailField() I now…
rotrotrot
  • 177
  • 1
  • 1
  • 6
10
votes
5 answers

Django Get Latest Entry from Database

I've got 2 questions, but they are related to the same topic. I know how to retrieve data from a for loop using template tags {% for status in status %} {{ status.status}} {% endfor %} However when I want to…
Jimmyn
  • 531
  • 1
  • 5
  • 27
10
votes
1 answer

select_related queryset with ModelSerializer in Django rest framework

I'm trying to use the "select_related" queryset method with DRF serializers, but this example is still doing a lot of sql queries. How can I get the related object "model_b" from select_related method? class Model_A(models.Model): title =…
10
votes
1 answer

do setting the max_length to a very large value consume extra space?

I have a field in the model, name = models.CharField(max_length=2000) and the data entered is, name='abc' the django model's max_length is set to 2000 while the entered data is only of length 3, Does the max_length reserves space for 2000…
All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111
10
votes
1 answer

Django - Runtime database switching

In my work we want to run a server with multiple databases. The databases switching should occur when you acces a url like http://myapp.webpage.com or http://other.webpage.com. We want to run only one server instance and at the moment of the HTTP…
10
votes
1 answer

How can i get the string representation from queryset in django

I have the queryset like this qs = User.objects.all() I am converting to dict like this qs.values('id', 'username') but instead of username i want to get the string representation. something like qs.values('id', '__str__')
user3214546
  • 6,523
  • 13
  • 51
  • 98
10
votes
1 answer

Maintaining South migrations on Django forks

I'm working on a pretty complex Django project (50+ models) with some complicated logic (lots of different workflows, views, signals, APIs, background tasks etc.). Let's call this project-base. Currently using Django 1.6 + South migrations and quite…
sttwister
  • 2,279
  • 1
  • 19
  • 23
10
votes
2 answers

Django migration file in an other app?

Let's imagine a following simplified Django project: /lib/python2.7/site-packages/externalapp/shop /myapp myapp also extends externalapp.shop.models models by adding a few fields. manage.py makemigrations did generated following schema…
David Unric
  • 7,421
  • 1
  • 37
  • 65
10
votes
2 answers

Extend user model Django REST framework 3.x.x

I am trying to extend the Django rest framework (version 3.x.x) with gender, created_at, updated_at fields that are defined in a separate model called UserProfile. When I try to update the UserProfile model instance including the nested User model…
Adam
  • 1,054
  • 1
  • 12
  • 26
10
votes
4 answers

Identifying new Model Instance in Django Save with UUID pk

If I have a model that has a UUID primary key and the the user may set the value on creation, is there any way to tell within the save method that the instance is new? Previous techniques of checking the auto assigned fields: In a django model…
Alex Rothberg
  • 10,243
  • 13
  • 60
  • 120