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
371
votes
8 answers

How do I filter query objects by date range in Django?

I've got a field in one model like: class Sample(models.Model): date = fields.DateField(auto_now=False) Now, I need to filter the objects by a date range. How do I filter all the objects that have a date between 1-Jan-2011 and 31-Jan-2011?
user469652
  • 48,855
  • 59
  • 128
  • 165
366
votes
28 answers

When saving, how can you check if a field has changed?

In my model I have : class Alias(MyBaseModel): remote_image = models.URLField( max_length=500, null=True, help_text=''' A URL that is downloaded and cached for the image. Only used when the alias is made …
Paul Tarjan
  • 48,968
  • 59
  • 172
  • 213
353
votes
15 answers

How do I clone a Django model instance object and save it to the database?

Foo.objects.get(pk="foo") In the database, I want to add another object which is a copy of the object above. Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do…
user426795
  • 11,073
  • 11
  • 35
  • 35
352
votes
4 answers

Django: Display Choice Value

models.py: class Person(models.Model): name = models.CharField(max_length=200) CATEGORY_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES) …
Shankze
  • 3,813
  • 3
  • 17
  • 11
352
votes
12 answers

Django auto_now and auto_now_add

For Django 1.1. I have this in my models.py: class User(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) When updating a row I get: [Sun Nov 15 02:18:12 2009] [error]…
Paul Tarjan
  • 48,968
  • 59
  • 172
  • 213
308
votes
9 answers

Django set default form values

I have a Model as follows: class TankJournal(models.Model): user = models.ForeignKey(User) tank = models.ForeignKey(TankProfile) ts = models.IntegerField(max_length=15) title = models.CharField(max_length=50) body =…
Mike
  • 7,769
  • 13
  • 57
  • 81
304
votes
8 answers

How to use "get_or_create()" in Django?

I'm trying to use get_or_create() for some fields in my forms, but I'm getting a 500 error when I try to do so. One of the lines looks like this: customer.source = Source.objects.get_or_create(name="Website") The error I get for the above code…
Stephen
  • 5,959
  • 10
  • 33
  • 43
300
votes
1 answer

How to query Case-insensitive data in Django ORM?

How can I query/filter in Django and ignore the cases of my query-string? I've got something like and like to ignore the case of my_parameter: MyClass.objects.filter(name=my_parameter)
Ron
  • 22,128
  • 31
  • 108
  • 206
298
votes
5 answers

Django values_list vs values

In Django, what's the difference between the following two: Article.objects.values_list('comment_id', flat=True).distinct() versus: Article.objects.values('comment_id').distinct() My goal is to get a list of unique comment ids under each Article.…
Hassan Baig
  • 15,055
  • 27
  • 102
  • 205
293
votes
9 answers

Fastest way to get the first object from a queryset in django?

Often I find myself wanting to get the first object from a queryset in Django, or return None if there aren't any. There are lots of ways to do this which all work. But I'm wondering which is the most performant. qs = MyModel.objects.filter(blah =…
Leopd
  • 41,333
  • 31
  • 129
  • 167
279
votes
16 answers

Django: Get list of model fields?

I've defined a User class which (ultimately) inherits from models.Model. I want to get a list of all the fields defined for this model. For example, phone_number = CharField(max_length=20). Basically, I want to retrieve anything that inherits from…
mpen
  • 272,448
  • 266
  • 850
  • 1,236
258
votes
11 answers

How to express a One-To-Many relationship in Django?

I'm defining my Django models right now and I realized that there wasn't a OneToManyField in the model field types. I'm sure there's a way to do this, so I'm not sure what I'm missing. I essentially have something like this: class…
Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411
251
votes
11 answers

How do I create a slug in Django?

I am trying to create a SlugField in Django. I created this simple model: from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() I then do this: >>> from mysite.books.models import…
Johnd
  • 6,441
  • 9
  • 29
  • 22
245
votes
2 answers

Automatic creation date for Django model form objects

What's the best way to set a creation date for an object automatically, and also a field that will record when the object was last updated? models.py: created_at = models.DateTimeField(False, True, editable=False) updated_at =…
Roger
  • 4,911
  • 6
  • 29
  • 26
245
votes
21 answers

Programmatically saving image to Django ImageField

Ok, I've tried about near everything and I cannot get this to work. I have a Django model with an ImageField on it I have code that downloads an image via HTTP (tested and works) The image is saved directly into the 'upload_to' folder (the…
T. Stone
  • 19,209
  • 15
  • 69
  • 97