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

Django1.4: How to use order_by in template?

Django1.4: How to use order_by in template? models.py from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class…
chobo
  • 4,830
  • 5
  • 23
  • 36
10
votes
1 answer

Django models are not ajax serializable

I have a simple view that I'm using to experiment with AJAX. def get_shifts_for_day(request,year,month,day): data= dict() data['d'] =year data['e'] = month data['x'] = User.objects.all()[2] return…
theycallmemorty
  • 12,515
  • 14
  • 51
  • 71
10
votes
1 answer

django accessing raw many to many created table fields

Model: class Subjects (models.Model): name = models.CharField(max_length=100) places = models.CharField(max_length=100) class Student (models.Model): name = models.CharField(max_length=40) lastname =…
Chris
  • 517
  • 1
  • 9
  • 22
10
votes
5 answers

Import app model class in another app model

I got 2 app: coworkers and services, each one with its own models.py In coworkers models.py, I can "from services.models import Services". When I try to "from coworkers.models import Status" in services models.py, I get this error…
Lucas Rezende
  • 2,516
  • 8
  • 25
  • 34
10
votes
2 answers

django model/modelForm - How to get dynamic choices in choiceField?

i'm experimenting with django and the builtin admin interface. I basically want to have a field that is a drop down in the admin UI. The drop down choices should be all the directories available in a specified directory. If i define a field like…
w--
  • 6,427
  • 12
  • 54
  • 92
10
votes
4 answers

Django Multi-Column Foreign Key

Is is possible to define foreign keys referencing multi columns in another model? For example one foreign key references a two-column index in the product table, and the SQL statement: FOREIGN KEY (product_category, product_id) REFERENCES…
S. Liu
  • 1,018
  • 2
  • 10
  • 25
10
votes
1 answer

Django field validation in Model and in Admin?

I want to define my own validation routine for a particular field of a Django model. I want the error message to be displayed in the admin form but I also want the same validation to take place if the entity is saved by own python code. Is there a…
Al Bundy
  • 1,599
  • 1
  • 14
  • 20
10
votes
2 answers

Django: How to follow ForeignKey('self') backwards

class Achievement(MyBaseModel): parent_achievement = models.ForeignKey('self', blank=True, null=True, help_text="An achievement that must be done before this one is achieved") # long name since parent is reserved I can do…
Paul Tarjan
  • 48,968
  • 59
  • 172
  • 213
10
votes
2 answers

django guardian, permissions and extending django auth groups to 'organization' models

django guardian https://github.com/lukaszb/django-guardian is a really well written object-level permissions app; and I have actually read up on and used quite a number of other django object level permissions app in various django projects. In a…
Calvin Cheng
  • 35,640
  • 39
  • 116
  • 167
10
votes
1 answer

how to add Permissions in Django to Models and Test it using the shell

I added the Meta class in my model and synchronized the DB then created an object in the shell it returns false so i really cant understand where is the error or what is missing is there some sort of configuration maybe in some other files .. class…
Karim Tarek
  • 391
  • 1
  • 5
  • 19
10
votes
1 answer

django - loaddata error when converting db from sqlite3 to postgres

I am trying to convert from a sqlite3 db to Postgres (so that I can have timezone-aware datetime fields with django 1.4). I dumped the data from the sqlite3 db. Then switched settings to point to the empty postgres db. Then ran syncdb, then south…
mb52089
  • 872
  • 2
  • 10
  • 24
9
votes
1 answer

Grouping Django model entries by day using its datetime field

I'm working with an Article like model that has a DateTimeField(auto_now_add=True) to capture the publication date (pub_date). This looks something like the following: class Article(models.Model): text = models.TextField() pub_date =…
Michael Mulich
  • 1,240
  • 14
  • 21
9
votes
3 answers

Excluding primary key in Django dumpdata with natural keys

How do you exclude the primary key from the JSON produced by Django's dumpdata when natural keys are enabled? I've constructed a record that I'd like to "export" so others can use it as a template, by loading it into a separate databases with the…
Cerin
  • 60,957
  • 96
  • 316
  • 522
9
votes
2 answers

How to soft delete many to many relation with Django

In my Django project, all entities deleted by the user must be soft deleted by setting the current datetime to deleted_at property. My model looks like this: Trip <-> TripDestination <-> Destination (many to many relation). In other words, a Trip…
Martin
  • 39,309
  • 62
  • 192
  • 278
9
votes
3 answers

django models recursive imports - how to resolve

I have a model project_phase: from django.db import models from django.utils import simplejson from core.models import pmo_review_task it references pmo_review_task (because it creates a pmo_review_task in its save ovewrite) from…
abolotnov
  • 4,282
  • 9
  • 56
  • 88