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
9
votes
4 answers

Django 3.2 AttributeError: 'TextField' object has no attribute 'db_collation'

I've an existing project on Django 3.1 and I upgraded my project to Django 3.2. I created an app called payment on my project. But When I make migrations. It trow an error AttributeError: 'TextField' object has no attribute 'db_collation' from…
9
votes
3 answers

Overriding get() method in models

Am trying to override get() method in my view as : broadcast = Broadcast.objects.get(request, pk = broadcast_id) In my model am overriding method as : class Broadcast(models.Model): person = models.ForeignKey(User) post =…
D_D
  • 383
  • 2
  • 5
  • 18
9
votes
1 answer

Using South to convert ForeignKey TO ManyToManyField not working out

I am using South to change a ForeignKey TO ManyToManyField in one of the models in Django but it is not working out as expected. # Original Schema class Item(models.Model): category = models.ForeignKey(Category, default=default_category) To be…
Chantz
  • 5,883
  • 10
  • 56
  • 79
9
votes
2 answers

Getting username in ImageField upload_to path

I would like to include the username in my upload_to directory path for when a user uploads an image. Here is what I currently have -- #model class Avatar(models.Model): avatar = models.ImageField(upload_to='images/%s' %(USERNAME) ) user =…
David542
  • 104,438
  • 178
  • 489
  • 842
9
votes
2 answers

How to set the maximum image size to upload image in django-ckeditor?

I am using django-ckeditor for my project to upload image along with text content. I used body = RichTextUploadingField(blank=True, null=True) in model. Now I want to restrict the user to upload large size images in content or larger than predefined…
9
votes
1 answer

Django - UserProfile m2m field in admin - error

My models: class UserProfile(models.Model): TYPES_CHOICES = ( (0, _(u'teacher')), (1, _(u'student')), ) user = models.ForeignKey(User, unique=True) type = models.SmallIntegerField(default=0, choices=TYPES_CHOICES,…
robos85
  • 2,484
  • 5
  • 32
  • 36
9
votes
2 answers

ManyToManyField and South migration

I have user profile model with M2M field class Account(models.Model): ... friends = models.ManyToManyField('self', symmetrical=True, blank=True) ... Now I need to know HOW and WHEN add each other as a FRIEND And I created a model for…
srusskih
  • 567
  • 4
  • 9
9
votes
3 answers

Django ORM: Equivalent of SQL `NOT IN`? `exclude` and `Q` objects do not work

The Problem I'm trying to use the Django ORM to do the equivalent of a SQL NOT IN clause, providing a list of IDs in a subselect to bring back a set of records from the logging table. I can't figure out if this is possible. The Model class…
FlipperPA
  • 13,607
  • 4
  • 39
  • 71
9
votes
3 answers

Incorrect results with `annotate` + `values` + `union` in Django

Jump to edit to see more real-life code example, that doesn't work after changing the query order Here are my models: class ModelA(models.Model): field_1a = models.CharField(max_length=32) field_2a = models.CharField(max_length=32) class…
Djent
  • 2,877
  • 10
  • 41
  • 66
9
votes
5 answers

Fixing the auth_permission table after renaming a model in Django

Every now and then, you have the need to rename a model in Django (or, in one recent case I encountered, split one model into two, with new/different names). (Yes, proper planning helps to avoid this situation). After renaming corresponding tables…
shacker
  • 14,712
  • 8
  • 89
  • 89
9
votes
2 answers

Same field, different choices in Django model subclasses

Is it possible to use different choices for subclasses of models? The following code should give you an idea class Clothing(models.Model): size = models.CharField(max_length=1) colour = models.CharField(max_length=1) SHIRT_SIZES = { …
Lexo
  • 470
  • 4
  • 20
9
votes
1 answer

django annotate with queryset

I have Users who take Surveys periodically. The system has multiple surveys which it issues at set intervals from the submitted date of the last issued survey of that particular type. class Survey(Model): name = CharField() description =…
Verbal_Kint
  • 1,366
  • 3
  • 19
  • 35
9
votes
1 answer

Django models - problem importing

I've refactored my models files into a module - this way it's much easier to maintain the code since it has grown quite a bit. The funny thing is though that it won't work for one of the classes that references another class that references the fist…
abolotnov
  • 4,282
  • 9
  • 56
  • 88
9
votes
1 answer

Displaying ForeignKey data in Django admin change/add page

I'm trying to get an attribute of a model to show up in the Django admin change/add page of another model. Here are my models: class Download(model.Model): task = models.ForeignKey('Task') class Task(model.Model): added_at =…
Brian Hicks
  • 6,213
  • 8
  • 51
  • 77
9
votes
1 answer

Non-relational field given in select_related: ' '. Choices are: (none)

I have two models from different apps: class Measure(models.Model): date = models.DateTimeField(default="2018-01-23 15:55") average = models.FloatField(default=0) class Sensor(models.Model): measure=models.ForeignKey(Measure,…
Alvaro
  • 1,430
  • 2
  • 23
  • 41
1 2 3
99
100