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

Django AttributeError 'datetime.date' object has no attribute 'utcoffset'

I'm a newbie in Django, so sorry if explanation of problem looks weird. I created a blog app within a Django project. models.py: from django.db import models class Blog(models.Model): title = models.CharField(max_length=255) pub_date =…
Dmitriy Fialkovskiy
  • 3,065
  • 8
  • 32
  • 47
10
votes
4 answers

Serialization of parent model including child models

I have models - Commodity, Clother and child models, as Acessories, Outwear, etc.: class Commodity(models.Model): atribute = models.CharField() class Clother(models.Model): commodity = models.ForeignKey(Commodity) clother_atribute =…
D. Make
  • 579
  • 2
  • 6
  • 23
10
votes
3 answers

In Django REST control serializer does not automatically remove spaces?

model.py class Msg(models.Model): content = models.CharField(max_length=1024, null=True) serializer.py class MessageSerializer(serializers.ModelSerializer): class Meta: model = Msg fields = ["content"] have…
10
votes
2 answers

How to make UUID field default when there's already ID field

I'm working on a project and problem is I've already created models with simple ID column but now my requirements are changed and I want to replace ID field (model) with UUID field I just updated my model: uuid = models.UUIDField(primary_key=True,…
10
votes
5 answers

Order items with the django-admin interface

Lets say I have a django model looking like this: class question(models.Model): order = models.IntegerField('Position') question = models.CharField(max_length= 400) answer = models.TextField() published = models.BooleanField() def…
Kai
  • 2,205
  • 3
  • 32
  • 43
10
votes
3 answers

How can the foreign field shows the name instead of its id?

In my models.py, there are two model, the AvailableArea has a foreign field refer to AddressRegion: class AddressRegion(models.Model): name = models.CharField(max_length=8) def __str__(self): return self.name def…
10
votes
1 answer

Can you register multiple ModelAdmins for a Model? Alternatives?

Say I have the Django model class: class Foo(models.Model): bar = models.CharField() baz = models.CharField() and the ModelAdmins: class Foo_Admin_1(admin.ModelAdmin): list_display = ['id','bar'] class Foo_Admin_2(admin.ModelAdmin): …
Tom Neyland
  • 6,860
  • 2
  • 36
  • 52
10
votes
3 answers

Changing the group of a model in Django Admin

For whatever reason I have three models related to authentication, but in Django Admin they show up in two different groups. For example: AUTHORIZATION ------------- Security Questions Users AUTHORIZATION AND…
cjones
  • 8,384
  • 17
  • 81
  • 175
10
votes
2 answers

Prevent DateRangeField overlap in Django model?

Now that Django supports the DateRangeField, is there a 'Pythonic' way to prevent records from having overlapping date ranges? Hypothetical use case One hypothetical use case would be a booking system, where you don't want people to book the same…
Brylie Christopher Oxley
  • 1,684
  • 1
  • 17
  • 34
10
votes
3 answers

Django filter related field using related model's custom manager

How can I apply annotations and filters from a custom manager queryset when filtering via a related field? Here's some code to demonstrate what I mean. Manager and models from django.db.models import Value, BooleanField class…
Ben
  • 885
  • 1
  • 12
  • 25
10
votes
2 answers

Django - Python 3 - "AssertionError: A model can't have more than one AutoField."

I'm getting crazy over this. I created my database with MySQLWorkbench This his my Schema Than I used the terminal command to get the model-code: $python3 manage.py inspectdb After passing the code to my models.py I try to use the models in the…
Anthony
  • 904
  • 1
  • 8
  • 15
10
votes
1 answer

Django - short non-linear non-predictable ID in the URL

I know there are similar questions (like this, this, this and this) but I have specific requirements and looking for a less-expensive way to do the following (on Django 1.10.2): Looking to not have sequential/guessable integer ids in the URLs and…
Anupam
  • 14,950
  • 19
  • 67
  • 94
10
votes
1 answer

"Apps aren't loaded yet" and "django.core.exceptions.ImproperlyConfigured" in Django?

This is the directory structure of my Django project. When I am running python code of importing a model:from scraping.models import LinkVendorStandard from the file "framework_product_processing.py" it throws this…
Javed
  • 5,904
  • 4
  • 46
  • 71
10
votes
3 answers

Django ORM: Override related_name of Field in Child Class

I get this exception: django.core.exceptions.FieldError: Local field 'ticket' in class 'SpecialPlugin' clashes with field of similar name from base class 'BasePlugin' Here are my models: class BasePlugin(models.Model): ticket =…
guettli
  • 25,042
  • 81
  • 346
  • 663
10
votes
5 answers

How to do text full history in Django?

I'd like to have the full history of a large text field edited by users, stored using Django. I've seen the projects: Django Full History (Google Code) Django ModelHistory, and Django FullHistory I've a special use-case that probably falls outside…
Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343