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

How do you specify a default for the Django ForeignKey field?

I’m trying to add a ForeignKey field to a Django model using South. I’m getting the following error: ValueError: You cannot add a null=False column without a default value. I did, in fact, specify a default value for the field, but I’m not sure I…
Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
10
votes
3 answers

How can I do a GROUP BY in Django without taking an aggregate function?

How can I do a GROUP BY in Django without invoking an aggregate function like Max, Sum, Avg, etc? In my case, I have a table that has columns like { local_path, parent, grandparent }, and I want to do SELECT local_path FROM ... WHERE grandparent =…
adam smith
  • 764
  • 7
  • 16
10
votes
3 answers

Django FileField default file

I have a model which contains FileField as below class Employer(models.Model): logo = models.FileField(storage=FileSystemStorage(location=settings.MEDIA_ROOT), upload_to='logos') The question is how can I add a default file like "{{…
brsbilgic
  • 11,613
  • 16
  • 64
  • 94
10
votes
2 answers

ImportError: 'tests' module incorrectly

I am working on unittest and when I type that : python manage.py test I got that : ImportError: 'tests' module incorrectly imported from '/home/user/Documents/myproject/dev/Project/tests'. Expected…
Peter
  • 123
  • 5
10
votes
1 answer

Django: Return list of dicts for values_list?

I've got this query: cities = ShippingPrice.objects.filter(city1__name__icontains=request.REQUEST.get('city','')).values_list('city1__id','city1__name').order_by('city1__name').distinct() Which returns a list of lists. It would be nice instead of…
mpen
  • 272,448
  • 266
  • 850
  • 1,236
10
votes
1 answer

How to compare two fields in a CheckConstraint

If this is my model: class Bid(models.Model): amount = models.DecimalField(max_digits=11, decimal_places=2) starting_bid = models.DecimalField(max_digits=11, decimal_places=2, null=True) How do I add a constraint that checks if the amount…
Ryan Eom
  • 337
  • 3
  • 14
10
votes
4 answers

Conditional Django migration based on a field only present in new version

My app that currently depends on Postgres and Django's Postgres-only JSONField. The field works well and I've no interest in another project, but I have prospective-users who want to use my app, but can't while it relies on Postgres. Django 3.1 has…
Oli
  • 235,628
  • 64
  • 220
  • 299
10
votes
2 answers

ManyToMany Relationship between two models in Django

I am trying to build a website that users can add the courses they are taking. I want to know how should I add the ManyToMany relationship. Such that we can get all users in a course based on the course code or instructor or any field. And we can…
ashes999
  • 1,234
  • 1
  • 12
  • 36
10
votes
4 answers

Django - How to check all the attributes of a queryset?

I am looking a way to get all the attributes of a variable after we set the value in it using queryset. For example...refer below code... using user.id or user.first_name i can get the value for that attribute. But if i want to check what all other…
10
votes
5 answers

Django Model Inheritance. Hiding or removing fields

I want to inherit a model class from some 3rd party code. I won't be using some of the fields but want my client to be able to edit the model in Admin. Is the best bet to hide them from Admin or can I actually prevent them being created in the first…
Andy Baker
  • 21,158
  • 12
  • 58
  • 71
10
votes
1 answer

Why define create_foo() in a Django models.Manager instead of overriding create()?

Reading the Django docs, it advices to make a custom creation method for a model named Foo by defining it as create_foo in the manager: class BookManager(models.Manager): def create_book(self, title): book = self.create(title=title) …
ruohola
  • 21,987
  • 6
  • 62
  • 97
10
votes
3 answers

Difference between auto_now_add and timezone.now as default value

What is the difference between auto_now_add and timezone.now (as default value) for models in Django? Example: create_date = models.DateTimeField(auto_now_add=True) and create_date = models.DateTimeField(default=timezone.now) ? UPD. I'm talking…
wowkin2
  • 5,895
  • 5
  • 23
  • 66
10
votes
2 answers

Python Error : (fields.E304) Reverse accessor for field clashes with reverse accessor for another field

Below is my models.py file in a Django project. Whenever I try to run the project I get the following error. Please assist as I have just started picking up django I tried changing the names of the foreign columns as suggested by the error but no…
ichthyocentaurs
  • 2,173
  • 21
  • 35
10
votes
2 answers

Django ImageField validation (is it sufficient)?

I have a lot of user uploaded content and I want to validate that uploaded image files are not, in fact, malicious scripts. In the Django documentation, it states that ImageField: "Inherits all attributes and methods from FileField, but also…
Ben
  • 15,010
  • 11
  • 58
  • 90
10
votes
3 answers

What is the value of self._db by default in Django?

Please see the following code: user.save(using=self._db) What is the default value of self._db for Django? Does this value default to what I've specified under default for database in my settings.py? I've found questions on Stack Overflow that…
user11719301