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
240
votes
14 answers

In a django model custom save() method, how should you identify a new object?

I want to trigger a special action in the save() method of a Django Model object when I'm saving a new record (not updating an existing record.) Is the check for (self.id != None) necessary and sufficient to guarantee the self record is new and not…
MikeN
  • 45,039
  • 49
  • 151
  • 227
237
votes
8 answers

How to 'bulk update' with Django?

I'd like to update a table with Django - something like this in raw SQL: update tbl_name set name = 'foo' where name = 'bar' My first result is something like this - but that's nasty, isn't it? list = ModelClass.objects.filter(name = 'bar') for obj…
Thomas Schwärzl
  • 9,518
  • 6
  • 43
  • 69
222
votes
21 answers

How do you serialize a model instance in Django?

There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?
Jason Christa
  • 12,150
  • 14
  • 58
  • 85
221
votes
10 answers

How to limit the maximum value of a numeric field in a Django model?

Django has various numeric fields available for use in models, e.g. DecimalField and PositiveIntegerField. Although the former can be restricted to the number of decimal places stored and the overall number of characters stored, is there any way to…
user82216
218
votes
8 answers

How to select a record and update it, with a single queryset in Django?

How do I run an update and select statements on the same queryset rather than having to do two queries: - one to select the object - and one to update the object The equivalent in SQL would be something like: update my_table set field_1 = 'some…
John
  • 21,047
  • 43
  • 114
  • 155
216
votes
6 answers

Django - How to rename a model field using South?

I would like to change a name of specific fields in a model: class Foo(models.Model): name = models.CharField() rel = models.ForeignKey(Bar) should change to: class Foo(models.Model): full_name = models.CharField() odd_relation…
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
210
votes
4 answers

Reload django object from database

Is it possible to refresh the state of a django object from database? I mean behavior roughly equivalent to: new_self = self.__class__.objects.get(pk=self.pk) for each field of the record: setattr(self, field, getattr(new_self, field)) UPDATE:…
Maxim Razin
  • 9,114
  • 7
  • 34
  • 33
208
votes
18 answers

How to pull a random record using Django's ORM?

I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. I'm using Django 1.0.2. While first 3 of them are…
kender
  • 85,663
  • 26
  • 103
  • 145
199
votes
6 answers

Django ManyToMany filter()

I have a model: class Zone(models.Model): name = models.CharField(max_length=128) users = models.ManyToManyField(User, related_name='zones', null=True, blank=True) And I need to contruct a filter along the lines of: u =…
Andy Baker
  • 21,158
  • 12
  • 58
  • 71
194
votes
8 answers

How to view corresponding SQL query of the Django ORM's queryset?

Is there a way I can print the query the Django ORM is generating? Say I execute the following statement: Model.objects.filter(name='test') How do I get to see the generated SQL query?
DjangoNewbe
191
votes
3 answers

How do I reference a Django settings variable in my models.py?

This is a very beginner question. But I'm stumped. How do I reference a Django settings variable in my model.py? NameError: name 'PRIVATE_DIR' is not defined Also tried a lot of other stuff including settings.PRIVATE_DIR settings.py: PRIVATE_DIR…
codingJoe
  • 4,713
  • 9
  • 47
  • 61
190
votes
6 answers

In Django, how does one filter a QuerySet with dynamic field lookups?

Given a class: from django.db import models class Person(models.Model): name = models.CharField(max_length=20) Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example: # Instead of: …
Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343
189
votes
15 answers

What is the most efficient way to store a list in the Django models?

Currently I have a lot of python objects in my code similar to the following: class MyClass(): def __init__(self, name, friends): self.myName = name self.myFriends = [str(x) for x in friends] Now I want to turn this into a Django…
grieve
  • 13,220
  • 10
  • 49
  • 61
184
votes
3 answers

Django dynamic model fields

I'm working on a multi-tenanted application in which some users can define their own data fields (via the admin) to collect additional data in forms and report on the data. The latter bit makes JSONField not a great option, so instead I have the…
GDorn
  • 8,511
  • 6
  • 38
  • 37
182
votes
35 answers

django.db.migrations.exceptions.InconsistentMigrationHistory

When I run python manage.py migrate on my Django project, I get the following error: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/hari/project/env/local/lib/python2.7/site-…