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
1350
votes
28 answers

What is the difference between null=True and blank=True in Django?

When we add a model field in Django we generally write: models.CharField(max_length=100, null=True, blank=True) The same is done with ForeignKey, DecimalField etc. What is the basic difference between: null=True only blank=True only null=True and…
user993563
  • 18,601
  • 10
  • 42
  • 55
957
votes
17 answers

How do I do a not equal in Django queryset filtering?

In Django model QuerySets, I see that there is a __gt and __lt for comparative values, but is there a __ne or != (not equals)? I want to filter out using a not equals. For example, for Model: bool a; int x; I want to do results =…
MikeN
  • 45,039
  • 49
  • 151
  • 227
808
votes
10 answers

How can I temporarily disable a foreign key constraint in MySQL?

Is it possible to temporarily disable constraints in MySQL? I have two Django models, each with a foreign key to the other one. Deleting instances of a model returns an error because of the foreign key constraint: cursor.execute("DELETE FROM…
jul
  • 36,404
  • 64
  • 191
  • 318
760
votes
14 answers

What is a "slug" in Django?

When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? I have read its definition below in this…
Jonas
  • 19,422
  • 10
  • 54
  • 67
703
votes
11 answers

What does on_delete do on Django models?

I'm quite familiar with Django, but I recently noticed there exists an on_delete=models.CASCADE option with the models. I have searched for the documentation for the same, but I couldn't find anything more than: Changed in Django 1.9: on_delete can…
All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111
608
votes
9 answers

How to filter empty or NULL names in a QuerySet?

I have first_name, last_name & alias (optional) which I need to search for. So, I need a query to give me all the names that have an alias set. Only if I could do: Name.objects.filter(alias!="") So, what is the equivalent to the above?
Val Neekman
  • 17,692
  • 14
  • 63
  • 66
574
votes
5 answers

How to define two fields "unique" as couple

Is there a way to define a couple of fields as unique in Django? I have a table of volumes (of journals) and I don't want more then one volume number for the same journal. class Volume(models.Model): id = models.AutoField(primary_key=True) …
Giovanni Di Milia
  • 13,480
  • 13
  • 55
  • 67
555
votes
12 answers

OneToOneField() vs ForeignKey() in Django

What's the difference between Django OneToOneField and ForeignKey?
redice
  • 8,437
  • 9
  • 32
  • 41
541
votes
17 answers

What's the best way to extend the User model in Django?

What's the best way to extend the User model (bundled with Django's authentication app) with custom fields? I would also possibly like to use the email as the username (for authentication purposes). I've already seen a few ways to do it, but can't…
Farinha
  • 17,636
  • 21
  • 64
  • 80
517
votes
6 answers

What's the difference between select_related and prefetch_related in Django ORM?

In Django doc: select_related() "follows" foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each relationship, and does the "joining" in Python. What does…
497
votes
13 answers

How to query as GROUP BY in Django?

I query a model: Members.objects.all() And it returns: Eric, Salesman, X-Shop Freddie, Manager, X2-Shop Teddy, Salesman, X2-Shop Sean, Manager, X2-Shop What I want is to know the best Django way to fire a group_by query to my database,…
simplyharsh
  • 35,488
  • 12
  • 65
  • 73
473
votes
10 answers

How to delete a record in Django models?

I want to delete a particular record like: delete from table_name where id = 1; How can I do this in a django model?
user426795
  • 11,073
  • 11
  • 35
  • 35
455
votes
18 answers

Convert Django Model object to dict with all of the fields intact

How does one convert a django Model object to a dict with all of its fields? All ideally includes foreign keys and fields with editable=False. Let me elaborate. Let's say I have a django model like the following: from django.db import…
Zags
  • 37,389
  • 14
  • 105
  • 140
431
votes
5 answers

Django Model() vs Model.objects.create()

What it the difference between running two commands: foo = FooModel() and bar = BarModel.objects.create() Does the second one immediately create a BarModel in the database, while for FooModel, the save() method has to be called explicitly to add…
0leg
  • 13,464
  • 16
  • 70
  • 94
412
votes
15 answers

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

I have a Person model that has a foreign key relationship to Book, which has a number of fields, but I'm most concerned about author (a standard CharField). With that being said, in my PersonAdmin model, I'd like to display book.author using…
Huuuze
  • 15,528
  • 25
  • 72
  • 91
1
2 3
99 100