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

How to update User object without creating new one?

Following works fine in shell: >>> from django.contrib.auth.models import User >>> user=User.objects.get(pk=1) >>> user.first_name = u'Some' >>> user.last_name = u'Name' >>> user.save() >>> user.first_name u'Some' >>> user.last_name u'Name' Then I…
Vlad T.
  • 2,568
  • 3
  • 26
  • 40
10
votes
1 answer

How to filter a dropdownlist in Django's admin when a selection is made on another dropdownlist

I have two dropdownlists in a Django admin site. For example, I have SelectCountry and SelectRegion. Region has a foreignkey relationship to Country. How do I ensure that when a Country is selected, the Regions are filtered based on that…
Lloyd Dube
  • 133
  • 2
  • 7
10
votes
4 answers

Django: filter a RawQuerySet

i've got some weird query, so i have to execute raw SQL. The thing is that this query is getting bigger and bigger and with lots of optional filters (ordering, column criteria, etc.). So, given the this query: SELECT DISTINCT Camera.* FROM Camera c …
santiagobasulto
  • 11,320
  • 11
  • 64
  • 88
10
votes
2 answers

Django pass object from view to next for processing

If you have 2 views, the first uses modelform that takes inputted information from the user (date of birth, name, phonenumber, etc), and the second uses this information to create a table. How would you pass the created object in the first view to…
10
votes
4 answers

Which is better: Foreign Keys or Model Inheritance?

I have this use case scenario: there are places which are either playgrounds, restaurants, theatres, pubs. the same place can have playgrounds, restaurants, theatres etc. there are couple of ways of implementing it: use foreign keys class…
whatf
  • 6,378
  • 14
  • 49
  • 78
10
votes
4 answers

Why use "through" argument for ManyToManyField in Django models?

Looking through the Django docs and trying to figure out the use of the "through" argument. Here is a link to the doc. The example: class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return…
Matt Parrilla
  • 3,171
  • 6
  • 35
  • 54
10
votes
5 answers

How to modify choices on Django Admin

I have a model that has a field named "state": class Foo(models.Model): ... state = models.IntegerField(choices = STATES) ... For every state, possible choices are a certain subset of all STATES. For example: if foo.state ==…
shanyu
  • 9,536
  • 7
  • 60
  • 68
10
votes
2 answers

Django - get distinct dates from timestamp

I'm trying to filter users by date, but can't until I can find the first and last date of users in the db. While I can have my script filter out dups later on, I want to do it from the outset using Django's distinct since it significantly reduces. I…
Edwin
  • 2,074
  • 1
  • 21
  • 40
10
votes
1 answer

Django ImageField issue

I have a similar model Class Student(models.Model): """A simple class which holds the basic info of a student.""" name = models.CharField(max_length=50) age = models.PositiveIntegerField() photo = models.ImageField(upload_to='foobar', blank=True,…
aatifh
  • 2,317
  • 4
  • 27
  • 30
10
votes
1 answer

howto add custom form into django administrator page inlines

Can I get a form into Django Administrator page, that I have defined in forms.py? Can I also get this form into Model inlines of Django Administrator page ? To be clear, this is what I call inline: class AnswerInline(admin.StackedInline): ...
user628154
  • 101
  • 1
  • 1
  • 4
10
votes
2 answers

Should I ForeignKey to Django User or a Profile model?

I'm wondering what people's thoughts are on joining models directly to the auth.User object vs to the user's profile model. I'm storing some different types of models which my user are adding in my app. App users will search for other users via…
Ludo
  • 2,739
  • 2
  • 28
  • 42
10
votes
2 answers

Django - Saving an image manually to an ImageField field

The following code takes an image after it gets saved and makes a thumbnail out of it: class Image(models.Model): image = models.ImageField(upload_to='images') thumbnail = models.ImageField(upload_to='images/thumbnails',…
Aziz Alfoudari
  • 5,193
  • 7
  • 37
  • 53
10
votes
1 answer

Django - Limit choices to something that depends on the instance

I have some foos which are organized into categories. For each category, I want to be able to select a winner foo. Hence I have models which look like this: class Category(models.Model): name = models.CharField(max_length=30) # More…
Andrea
  • 20,253
  • 23
  • 114
  • 183
10
votes
3 answers

Abstract Models and Foreign Keys in Django

I am working on a django project in which I create a set of three abstract models that I will use for a variety of apps later on. The problem I am running into is that I want to connect those models via ForeignKey but django tells me that it can't…
phoxley
  • 464
  • 8
  • 19
10
votes
2 answers

Dynamic Meta attributes for Django Models?

I am trying to add a dynamic Meta attribute to all of my Django models using model inheritance, but I can't get it to work. I have a permission that I want to add to all my models like this: class ModelA(models.Model): class Meta: …
gerdemb
  • 11,275
  • 17
  • 65
  • 73