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

HTTP/1.0 301 Moved Permanently-Django

I have created a API using djangorestframework, but when i run it in terminal by using python manage.py runserver command it shows "HTTP/1.0 301 Moved Permanently" error.This the Message which it shows But the cool thing is , when i run it in…
10
votes
1 answer

Django: foreign key queries

I'm learning Django and trying to get the hang of querying foreign keys across a bridging table. Apologies if this is a duplicate, I haven't been able to find the answer by searching. I've got models defined as follows class Place(models.Model): …
AP257
  • 89,519
  • 86
  • 202
  • 261
10
votes
6 answers

ValueError in Django when running the "python manage.py migrate" command

I needed to add more fields to Django's User model, so I created a custom model class (named Accounts in an app named accounts) that extends Django's AbstractUser class. After that, I updated my settings.py file, defining the AUTH_USER_MODEL…
Inyavic Sage
  • 145
  • 1
  • 2
  • 11
10
votes
1 answer

Django present related_name objects in admin model

I have the following models: class A(models.Model): name = models.CharField(max_length=100) c = models.ForeignKey(C, related_name='letters_c', null=True, blank=True) ... class B(models.Model): id= models.CharField(max_length=200,…
user2552806
10
votes
3 answers

Python: interact with complex data warehouse

We've worked hard to work up a full dimensional database model of our problem, and now it's time to start coding. Our previous projects have used hand-crafted queries constructed by string manipulation. Is there any best/standard practice for…
bukzor
  • 37,539
  • 11
  • 77
  • 111
10
votes
1 answer

Django update ViewSet

Currently I am developing a image gallery django project. The user can upload images, and later upload a 'result' to each of the images. I know that I have to override the update(...) function, but I think I need help here with the…
10
votes
1 answer

Representing a multi-select field for weekdays in a Django model

I've been searching for an elegant way to represent a multi-select weekday field (Mon, Tues, Wed...) in a Django model. I was initially thinking of going integer field using bitwise math but I am not sure if this would be the way to go. This would…
Belmin Fernandez
  • 8,307
  • 9
  • 51
  • 75
10
votes
5 answers

How to import datetime module in Django?

I've learned some basic in Django but I stucked in this tutorial: http://docs.djangoproject.com/en/dev/intro/tutorial02/#customize-the-admin-change-list Error found when was_published_today added: global name 'datetime' is not defined Some search…
Sinama
  • 171
  • 1
  • 1
  • 3
10
votes
1 answer

Can model properties be displayed in a template

I am looking to display a model property in a template, which uses an inlineformset_factory. Is this even possible? I have not come across any example. I am trying to display 'json_data' in my template class RecipeIngredient(models.Model): …
iJK
  • 4,655
  • 12
  • 63
  • 95
10
votes
2 answers

Django - how to extend 3rd party models without modifying

I want to add a column to a database table but I don't want to modify the 3rd party module in case I need/decide to upgrade the module in the future. Is there a way I can add this field within my code so that with new builds I don't have to add the…
user409880
  • 103
  • 1
  • 4
10
votes
1 answer

How to pass callable in Django 1.9

Hi i am new in Python and Django and I follow the django workshop guide. I just installed Python 3.5 and Django 1.9 and get a lot of error messages ... Just now I found a lot of dokumentations but now stuck. I want to add views and and so I added…
Pompi
  • 123
  • 1
  • 7
10
votes
6 answers

Filter related field against another related model's M2M relationship in Django

So I have a booking system. Agents (the people and organisations submitting bookings) are only allowed to make booking in the categories we assign them. Many agents can assign to the same categories. It's a simple many-to-many. Here's an idea of…
Oli
  • 235,628
  • 64
  • 220
  • 299
10
votes
1 answer

How to automatically save the headline for every new article provided my 3rd party js script is embed on a website

I am working on a something similar to Disqus, and I created a third-party javascript snippet which the user will embed in the website and have a rating widget for each article. Users can rate the article using the widget. Everything is working, the…
10
votes
3 answers

How to create double and long text field from django models

How to create a double field in mysql using django models. i run into this error and also how to create a longtext datatype with django class Test(models.Model): maxcount = models.DoubleField(null=True) ## double DEFAULT NULL, cs =…
Rajeev
  • 44,985
  • 76
  • 186
  • 285
10
votes
6 answers

How to make Django Queryset that selects records with max value within a group

Here is my Django class: class MyClass(models.Model): my_integer = models.IntegerField() created_ts = models.DateTimeField(default=datetime.utcnow, editable=False) I would like to retrieve the instances of MyClass that have the latest…
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272