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
1 answer

django model with two generic (content_type) foreign keys?

I'm trying to create a mapping table between two generic (content_type) references, one for "agents" and one for "resources". So I take the usual way I make a generic foreign key : content_type = models.ForeignKey(ContentType) object_id =…
interstar
  • 26,048
  • 36
  • 112
  • 180
9
votes
3 answers

Django how to delete user's profile and posts and all assocation after user deleted?

I'm writing a django project. And want to know after user deletes his own account, is there a way django build-in to auto delete all object related to this user(e.g. some generic foreign_key)? Or I should use signal "post_delete" to delete every…
Xinghan
  • 255
  • 1
  • 3
  • 8
9
votes
1 answer

Django model error- "TypeError: 'xxx' is an invalid keyword argument for this function

I get the error: TypeError: 'person' is an invalid keyword argument for this function My model is: class Investment(models.Model): company = models.ManyToManyField("Company", related_name ="Investments_company") financial_org =…
Riku
  • 2,223
  • 2
  • 17
  • 20
9
votes
4 answers

django: sqlite3.OperationalError: no such table

i don't now why, but from one day to another y started to have problems when i tried to run the tests. I'm using django 1.1 (customer requirements) and when i running test whith: python manage.py test --setting=settingsTest it throw: Traceback…
gsoriano
  • 386
  • 1
  • 4
  • 6
9
votes
3 answers

Reverse Inlines in Django Admin

I have 2 models as follows. Now I need to inline Model A on Model B's page. models.py class A(models.Model): name = models.CharField(max_length=50) class B(models.Model): name = models.CharField(max_length=50) a =…
Gathole
  • 892
  • 1
  • 13
  • 24
9
votes
7 answers

Django tastypie and GenericForeignKey

I have Page model with GFK. class Page(models.Model): title = models.CharField(max_length=200) content_type = models.ForeignKey(ContentType,null=True,blank=True) object_id = models.CharField(max_length=255,null=True,blank=True) …
moskrc
  • 1,220
  • 1
  • 12
  • 23
9
votes
1 answer

In Django, how can you get all related objects with a particular User foreign Key

I have something like this: class Video(models.Model): user = models.ForeignKey(User, related_name='owner') ... and I'm trying to access all the videos a particular user has by doing something like: u =…
9-bits
  • 10,395
  • 21
  • 61
  • 83
9
votes
1 answer

Django custom form field initial data

I am having trouble understanding how to initialize a custom form field in a django view. For example: http://djangosnippets.org/snippets/907/ from datetime import date, datetime from calendar import monthrange class…
Chris
  • 11,780
  • 13
  • 48
  • 70
9
votes
2 answers

Django: making relationships in memory without saving to DB

I have some models with relationships like this: class Item(model.Model): name = models.CharField() class Group(models.Model): item = models.ManyToManyField(Item) class Serie(models.Model): name = models.CharField() chart =…
Facundo Casco
  • 10,065
  • 8
  • 42
  • 63
9
votes
4 answers

AttributeError: type object ... has no attribute 'objects'

fragment of models.py class Hardware_type(models.Model): type = models.CharField(blank = False, max_length = 50, verbose_name="Type") description = models.TextField(blank = True, verbose_name="Description") slug = models.SlugField(unique…
Kubas
  • 976
  • 1
  • 15
  • 34
9
votes
4 answers

PROTECT vs RESTRICT for on_delete (Django)

I read the django documentation about PROTECT and RESTRICT to use with "on_delete". PROTECT Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError. Example: class MyModel(models.Model): …
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
9
votes
2 answers

How do you handle a PATCH request from HTMX in Django?

I would like to send a PATCH request to my app but I'm not sure how to consume the request in Django. I am currently getting the following error. AttributeError: 'WSGIRequest' object has no attribute 'PATCH' The input field in the HTMX file looks…
Ben
  • 2,143
  • 2
  • 19
  • 27
9
votes
2 answers

ModelForm with a reverse ManytoMany field

I'm having trouble getting ModelMultipleChoiceField to display the initial values of a model instance. I haven't been able to find any documentation about the field, and the examples I've been reading are too confusing. Django:…
Edd
  • 1,925
  • 1
  • 17
  • 15
9
votes
2 answers

How to implement Django multiple user types, while one user can have different role according to the project he/she is working on?

I couldn't find a solution to my problem and would appreciate comments/help on this. I would like to develop a multiple user type model in Django, along the lines of this video where the author is using Django Proxy Models. Situation I have a list…
lhoupert
  • 584
  • 8
  • 25
9
votes
3 answers

django - DecimalField max_digits, decimal_places explained

So I'm just starting out with Django and using it to store forex prices which are represented as 1.21242, 1.20641, etc... model.py from django.db import models # Create your models here. class ForexPrice(models.Model): openPrice =…
Farhan Ahmad
  • 5,148
  • 6
  • 40
  • 69