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
1 answer

Django-reversion and south compatibility

Does django-reversion work well with south migrations? Are django-reversion and south compatible? Current versions: - reversion - 1.2.1 - south - 0.7.1
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
10
votes
0 answers

Django 1.7 + PostgreSQL needs restart to recognize new database entries

I have a Django page called /candidates which is supposed to fetch all Candidate entries in the database. The problem is whenever I create a new Candidate entry, the /candidates page doesn't show anything but when I check django-admin I can verify…
DigitalDouble
  • 1,747
  • 14
  • 26
10
votes
1 answer

Django creating a custom model field

I am trying to create a custom field in Django which will take a decimal currency value (example: £1.56) and save it in the database as an Integer (example: 156) to store currency values. This is what I have so far (I have put fixed values to…
LondonAppDev
  • 8,501
  • 8
  • 60
  • 87
10
votes
4 answers

How to check the type of a many-to-many-field in django?

How can you check the type of a many-to-many-field in django? I wanted to do it this way: import django field.__class__ == django.db.models.fields.related.ManyRelatedManager This doesn't work, because the class ManyRelatedManager can't be…
amann
  • 5,449
  • 4
  • 38
  • 46
10
votes
2 answers

Force django to create tables using MYISAM storage engine

How to force django to use MYISAM storage engine when creating database using syncdb command? This page does not help much to shed light in this issue. MYISAM is the perfect choice since the database is almost only used for reading and MYISAM is…
bman
  • 5,016
  • 4
  • 36
  • 69
10
votes
3 answers

What is the meaning of string argument in django model's Field?

Just learning django, I'm reading this tutorial and getting confused at this part: class Question(models.Model): pub_date = models.DateTimeField('date published') Having searching its documentation, still can't figure out what does 'date…
null
  • 8,669
  • 16
  • 68
  • 98
10
votes
4 answers

Django model translation : store translations in database or use gettext?

I'm in a Django website's I18N process. I've selected two potentially good django-apps : django-modeltranslation which modifies the db schema to store translations django-dbgettext which inspect db content to create .po files and uses gettext From…
10
votes
2 answers

Django REST API to expose images

I have a django app and I want to expose the model images, such that when I request /image/school_id/400 it will return the image of school with id school_id cropped and resized to a box 400x400 px. Here is what I tried @api_view(['GET',…
Alexxio
  • 1,091
  • 3
  • 16
  • 38
10
votes
2 answers

Django Model OneToOneField without creating additional _id database column

I'm working with an Account model and I want to inner join it with a Settings model without having to create an additional settings_id column in my Account model, because the PK on the Account table matches the PK on the settings table exactly. I've…
Cory Danielson
  • 14,314
  • 3
  • 44
  • 51
10
votes
4 answers

Programmatically specifying Django model attributes

I would like to add attributes to a Django models programmatically. At class creation time (the time of the definition of the model class). The model is not going to change after that in run time. For instance, lets say I want to define a Car model…
mojbro
  • 1,509
  • 13
  • 13
10
votes
1 answer

Django Rest Framework SerializerMethodField Pass Extra Argument

I have a model method that requires the request user to be pass in as an extra argument: Model Method: def has_achieved(self, user): return AwardLog.objects.filter(user=user, badge=self).count() > 0 Using the Django Rest Framework I want to…
Prometheus
  • 32,405
  • 54
  • 166
  • 302
10
votes
2 answers

Django filter multiple columns with a list of tuples

I have a simple model with 2 fields: class Simple(Model) class Meta: index_together = True a = IntField() b = IntField() I would like to generate an SQL query for tuples of values for a,b. e.g. select * from SimpleModel where…
idanzalz
  • 1,740
  • 1
  • 11
  • 18
10
votes
2 answers

Django Admin filtering ForeignKey dropdown based on another field

I have 3 Models: class FileType(models.Model): name=models.CharField(max_length=128) class ManagedFile(models.Model): type = models.ForeignKey(FileType) content = models.FileField(upload_to=path_maker) class Tag(models.Model): …
Matthew Scouten
  • 15,303
  • 9
  • 33
  • 50
10
votes
1 answer

Django - Get the first attribute from all objects in a Model

I am trying to get a list of the content of one attribute from all objects in a model. For now, I am doing this: titles_list = [] for item in A.objects.all(): titles_list.append(item.title) print titles_list Is there a more interesting…
Erwan
  • 1,055
  • 1
  • 12
  • 26
10
votes
2 answers

Want to use my existing mysql database with django

I have created a django project and now rendering templates. I have a mysql database already with loads of tables and data. From what i saw in the tutorials, the model concept of python is interesting and easy however i am not able to use it here,…
Gopi
  • 216
  • 1
  • 3
  • 11