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
182
votes
7 answers

Why doesn't django's model.save() call full_clean()?

I'm just curious if anyone knows if there's good reason why django's orm doesn't call 'full_clean' on a model unless it is being saved as part of a model form. Note that full_clean() will not be called automatically when you call your model’s…
Aaron
  • 4,206
  • 3
  • 24
  • 28
182
votes
3 answers

Django - filtering on foreign key properties

I'm trying to filter a table in Django based on the value of a particular field of a ForeignKey. For example, I have two models: class Asset(models.Model): name = models.TextField(max_length=150) project = models.ForeignKey('Project') class…
Fraser Graham
  • 4,650
  • 4
  • 22
  • 42
181
votes
10 answers

Django: Get model from string?

In Django, you can specify relationships like: author = ForeignKey('Person') And then internally it has to convert the string "Person" into the model Person. Where's the function that does this? I want to use it, but I can't find it.
mpen
  • 272,448
  • 266
  • 850
  • 1,236
181
votes
8 answers

How to get the currently logged in user's id in Django?

How to get the currently logged-in user's id? In models.py: class Game(models.model): name = models.CharField(max_length=255) owner = models.ForeignKey(User, related_name='game_user', verbose_name='Owner') In views.py: gta =…
k44
  • 1,855
  • 3
  • 13
  • 7
181
votes
13 answers

Django dump data for a single model?

Can I perform a dumpdata in Django on just a single model, rather than the whole app, and if so, how? For an app it would be: python manage.py dumpdata myapp However, I want some specific model, such as "myapp.mymodel" to be dumped. The reason…
nategood
  • 11,807
  • 4
  • 36
  • 44
179
votes
6 answers

Django: Why do some model fields clash with each other?

I want to create an object that contains 2 links to Users. For example: class GameClaim(models.Model): target = models.ForeignKey(User) claimer = models.ForeignKey(User) isAccepted = models.BooleanField() but I am getting the following…
Oleg Tarasenko
  • 9,324
  • 18
  • 73
  • 102
178
votes
7 answers

Django override save for model only in some cases?

Before saving model I'm re-size a picture. But how can I check if new picture added or just description updated, so I can skip rescaling every time the model is saved? class Model(model.Model): image=models.ImageField(upload_to='folder') …
Pol
  • 24,517
  • 28
  • 74
  • 95
176
votes
6 answers

How to filter objects for count annotation in Django?

Consider simple Django models Event and Participant: class Event(models.Model): title = models.CharField(max_length=100) class Participant(models.Model): event = models.ForeignKey(Event, db_index=True) is_paid =…
rudyryk
  • 3,695
  • 2
  • 26
  • 33
175
votes
10 answers

Unique fields that allow nulls in Django

I have model Foo which has field bar. The bar field should be unique, but allow nulls in it, meaning I want to allow more than one record if bar field is null, but if it is not null the values must be unique. Here is my model: class…
Sergey Golovchenko
  • 18,203
  • 15
  • 55
  • 72
174
votes
6 answers

How to create an object for a Django model with a many to many field?

My model: class Sample(models.Model): users = models.ManyToManyField(User) I want to save both user1 and user2 in that model: user1 = User.objects.get(pk=1) user2 = User.objects.get(pk=2) sample_object = Sample(users=user1,…
Sai Krishna
  • 7,647
  • 6
  • 29
  • 40
174
votes
12 answers

Get model's fields in Django

Given a Django model, I'm trying to list all of its fields. I've seen some examples of doing this using the _meta model attribute, but doesn't the underscore in front of meta indicate that the _meta attribute is a private attribute and shouldn't be…
Joe J
  • 9,985
  • 16
  • 68
  • 100
173
votes
6 answers

Django - Circular model import issue

I'm really not getting this, so if someone could explain how this works I'd very much appreciate it. I have two applications, Accounts and Theme... here is my settings list: INSTALLED_APPS = ( 'django.contrib.auth', …
Hanpan
  • 10,013
  • 25
  • 77
  • 115
170
votes
6 answers

What is the SQL ''LIKE" equivalent on Django ORM queries?

What is the equivalent of the following SQL statement in Django? SELECT * FROM table_name WHERE string LIKE pattern; I tried this: result = table.objects.filter( pattern in string ) but it didn't work. How can I implement it?
Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
170
votes
14 answers

.filter() vs .get() for single object? (Django)

I was having a debate on this with some colleagues. Is there a preferred way to retrieve an object in Django when you're expecting only one? The two obvious ways are: try: obj = MyModel.objects.get(id=1) except MyModel.DoesNotExist: # We…
Cory
  • 22,772
  • 19
  • 94
  • 91
167
votes
8 answers

Create Django model or update if exists

I want to create a model object, like Person, if person's id doesn't not exist, or I will get that person object. The code to create a new person as following: class Person(models.Model): identifier = models.CharField(max_length = 10) name…
user1687717
  • 3,375
  • 7
  • 26
  • 29