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
11
votes
3 answers

How to add bi-directional manytomanyfields in django admin?

In my models.py i have something like: class LocationGroup(models.Model): name = models.CharField(max_length=200) class Report(models.Model): name = models.CharField(max_length=200) locationgroups =…
Jack Ha
  • 19,661
  • 11
  • 37
  • 41
11
votes
1 answer

Django ModelForm Validation

Trying to solve an interesting problem right now. I have a Django model with an image field that's not required, but is set to a default value when a new model instance is created. class Product(models.Model): image =…
rolling stone
  • 12,668
  • 9
  • 45
  • 63
11
votes
1 answer

Getting all objects of model except

Let the models class: class MyModel(models.Model): name = models.CharField(max_length=200) category = models.CharField(max_length=200) I want to get all the objects of MyModel except those with a specific category. I'm using this code: [mm…
msampaio
  • 3,394
  • 6
  • 33
  • 53
11
votes
1 answer

Django reversion does not save revisions made in shell

I did the initial installation steps and created the initial revisions, but then when I save a model in django shell, the new revision is not created: In [1]: s = Shop.objects.all()[0] In [2]: import reversion In [3]: s.name = 'a' In [4]:…
culebrón
  • 34,265
  • 20
  • 72
  • 110
11
votes
4 answers

Django Admin -> Change Order of Fields, including Inline Fields

I have a "Person" Model which has a one-to-many Relations to other Models, for instance Address. I want to edit these models on the same page as Person, which I can already do via inlines. But I also want to change the order of the fields. I want…
nina
11
votes
3 answers

Unit Testing with Django Models and a lot of relations involved

Or, "How to design your Database Schema for easy Unit testing?" By the way, there is a very similar question to this here: How to test Models in Django with Foreign Keys I'm trying to follow TDD methodology for a project that uses the framework…
javier
  • 1,705
  • 2
  • 18
  • 24
11
votes
1 answer

django model validation not working

I have the following model: class CardInfo(models.Model): custid = models.CharField(max_length=30, db_index=True, primary_key = True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) street =…
Vivek S
  • 5,384
  • 8
  • 51
  • 72
11
votes
2 answers

django model: objects.all().delete() doesn't

I am trying to clear out and reload a table in my django model, and >>> models.PuzzleSum.objects.all().count() 2644 >>> models.PuzzleSum.objects.all().delete() >>> models.PuzzleSum.objects.all().count() 2535 ... wtf? Always the magic number 109. I…
AlanL
  • 626
  • 1
  • 6
  • 15
11
votes
5 answers

In Django, how can I order by a multiple-choice CharField in arbitrary not alphabetical order?

Imagine a model Shirts with a size CharField, with values limited to a small number of choices, e.g. 'small', 'medium', 'large', 'xlarge' etc. To get the shirts grouped by size, you'd do: Shirts.objects.order_by('size') But Django will (naturally)…
Ghopper21
  • 10,287
  • 10
  • 63
  • 92
11
votes
2 answers

Passing Instance to Django formset

How to pass a instance to the Django formset, The Scenario is like this. I have updated multiple rows by using a formset and, in a later stage i need to edit those values which i added earlier.(Editing) q =…
11
votes
4 answers

How to get max value in django ORM

>>> AuthorizedEmail.objects.filter(group=group).values('added') [{'added': datetime.datetime(2012, 5, 19, 13, 8, 7)}, {'added': datetime.datetime(2012, 5, 19, 13, 8, 7)}, {'added': datetime.datetime(2012, 5, 19, 13, 7, 23)}, {'added':…
David542
  • 104,438
  • 178
  • 489
  • 842
11
votes
2 answers

Can't subtract datetime and timestamp in django?

I have a field timestamp = models.DateTimeField(auto_now_add=True) in the db. I want to find the difference between that timestamp and datetime.now(). When I tried datetime.now() - timestamp, I get the error: can't subtract offset-naive and…
iCodeLikeImDrunk
  • 17,085
  • 35
  • 108
  • 169
11
votes
2 answers

Consuming a RESTful API with Django

I'm building a Django application that needs to interact with a 3rd party RESTful API, making various GETs, PUTs, etc to that resource. What I'm looking for is a good way to represent that API within Django. The most obvious, but perhaps less…
devights
  • 263
  • 1
  • 4
  • 11
11
votes
5 answers

Django - DatabaseError: No such table

I defined two models: class Server(models.Model): owners = models.ManyToManyField('Person') class Person(models.Model): name = models.CharField(max_length=50) admin.site.register(Server) admin.site.register(Person) After that I even…
varesa
  • 2,399
  • 7
  • 26
  • 45
11
votes
3 answers

Compare date and datetime in Django

I have a model with a datetime field: class MyModel(models.Model): created = models.DateTimeField(auto_now = True) I want to get all the records created today. I tried: MyModel.objects.all().filter(created =…
Just_Mad
  • 4,029
  • 3
  • 22
  • 30