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

How to set default value for new model field in existing model with data

I have a small django model with two fields. There is already data in the database for this model. class MetaDataValue(Model): metadata_id = models.ForeignKey(MetaData, on_delete=models.CASCADE,) value = models.CharField('value',…
user1045680
  • 815
  • 2
  • 9
  • 19
9
votes
5 answers

Django: How to migrate from ManyToMany to ForeignKey?

I'm building a REST API and server using Django and Django Rest Framework. We are using a postgres database. I need to simplify a badly designed relation. We have a model (House) that has a ManyToMany relationship to another (City). In reality it…
J. Hesters
  • 13,117
  • 31
  • 133
  • 249
9
votes
1 answer

Django: How to add 2 days to an existing date entered by user

I am trying to add a a payment due date 2 days after the event class Payment(models.Model): event_date = models.DateField() payment_due_date = models.DateField() class Meta: ordering = ["payment_due_date"] …
Samir Tendulkar
  • 1,151
  • 3
  • 19
  • 47
9
votes
0 answers

Django: UUID in automatic ManyToMany fields

I want to use UUIDs for database ids instead of autoincrement integers. I understand that this can be done by overriding the id in the Model class, for example: from django.db import models class Publication(models.Model): id =…
EMS
  • 1,033
  • 1
  • 9
  • 11
9
votes
3 answers

django - django-taggit form

I would like to use django-taggit (click here ). The documentation ( click here) talks about using ModelForm to generate the form but I have already my form that I would like to use. Let's say if I have something like this: forms.py class…
avatar
  • 12,087
  • 17
  • 66
  • 82
9
votes
4 answers

Formatting DateTimeField in Django

When saving timestamp in Django's DateTimeField using auto_now_add this way: creation_timestamp = models.DateTimeField(auto_now_add=True) the field is saved with miliseconds: 2018-11-20T15:58:44.767594-06:00 I want to format this to be displayed…
Stan Reduta
  • 3,292
  • 5
  • 31
  • 55
9
votes
4 answers

Django - Group By with Date part alone

MyModel.objects.filter(created_at__gte='2011-03-09', created_at__lte='2011-03-11').values('created_at','status').annotate(status_count=Count('status')) The above query has the problem with the created_at datetime field. Is it possible to tune the…
Siva Arunachalam
  • 7,582
  • 15
  • 79
  • 132
9
votes
1 answer

How to safely access request object in Django models

What I am trying to do: I am trying to access request object in my django models so that I can get the currently logged in user with request.user. What I have tried: I found a hack on this site. But someone in the comments pointed out not to do it…
Ahtisham
  • 9,170
  • 4
  • 43
  • 57
9
votes
1 answer

error :object can't be deleted because its id attribute is set to None

Trying to Delete an object using shell in django. How do i delete the object say "Ron"? I use the following command: t.delete('Ron')
AbrarWali
  • 607
  • 6
  • 19
9
votes
3 answers

Django objects uniqueness hell with M2M fields

class Badge(SafeDeleteModel): owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.PROTECT) restaurants = models.ManyToManyField(Restaurant) …
David Dahan
  • 10,576
  • 11
  • 64
  • 137
9
votes
3 answers

How to work with unsaved many-to-many relations in django?

I have a couple of models in django which are connected many-to-many. I want to create instances of these models in memory, present them to the user (via custom method-calls inside the view-templates) and if the user is satisfied, save them to the…
qollin
  • 1,271
  • 1
  • 14
  • 15
9
votes
5 answers

Storing a binary hash value in a Django model field

I have a twenty byte hex hash that I would like to store in a django model. If I use a text field, it's interpreted as unicode and it comes back garbled. Currently I'm encoding it and decoding it, which really clutters up the code, because I have…
mbarkhau
  • 8,190
  • 4
  • 30
  • 34
9
votes
2 answers

Django Models for Time Series Data

My friends and I building an app that buy and sell stocks and we want to keep the historical prices of each stocks that we have in our possession by the end of day. The 3 most important fields are the ticker symbol and the price and the date. For…
Alan
  • 313
  • 4
  • 14
9
votes
3 answers

Django and ChartJS

I'm trying to understand if it it's possible to incorporate dynamic data into a Django Chart JS architecture. I went through a couple of tutorials and ultimately got Django to work with ChartJS and it's very good when I'm able to hard code values…
Steve Smith
  • 1,019
  • 3
  • 16
  • 38
9
votes
1 answer

Django + Influxdb

I have tseries data that has been stored in influxdb, I would like to serve this data through a web API and therefore are considering Django framework and its REST API framework as a solution. At the moment, there is no known support for Influxdb on…
qboomerang
  • 1,931
  • 3
  • 15
  • 20
1 2 3
99
100