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

Limit number of relationship in ManyToManyField in django

I am using ManyToMany relationship in my code in a scenario where i have showrooms and their categories. Now a showroom can fall into maximum three categories and i have to validate it while saving. Below is my code: ##models.py class…
Rakesh Kumar
  • 157
  • 1
  • 13
10
votes
4 answers

Model has either not been installed or is abstract

When I try to migrate my code I get this error. Here are my code and classes: from django.db import models from core.models import Event class TicketType(models.Model): name = models.CharField(max_length=45) price =…
gabi
  • 1,324
  • 4
  • 22
  • 47
10
votes
3 answers

How can I change existing token in the authtoken of django-rest-framework?

Saving fails: from rest_framework.authtoken.models import Token token = Token.objects.get(user=user1) token.key = '1' token.save() gives IntegrityError: duplicate key value violates unique constraint "authtoken_token_user_id_key"
nmb.ten
  • 2,158
  • 1
  • 20
  • 18
10
votes
4 answers

django form error messages not showing

So I have my view: def home_page(request): form = UsersForm() if request.method == "POST": form = UsersForm(request.POST) if form.is_valid(): form.save() c = {} c.update(csrf(request)) …
SilentDev
  • 20,997
  • 28
  • 111
  • 214
10
votes
1 answer

how to get list of objects involving many to many relation in django

I have the following models: class Committee(models.Model): customer = models.ForeignKey(Customer, related_name="committees") name = models.CharField(max_length=255) members = models.ManyToManyField(member, through=CommitteeMember,…
Atma
  • 29,141
  • 56
  • 198
  • 299
10
votes
2 answers

Django Queryset - extracting only date from datetime field in query (inside .value() )

I want to extract some particular columns from django query models.py class table id = models.IntegerField(primaryKey= True) date = models.DatetimeField() address = models.CharField(max_length=50) city = models.CharField(max_length=20) …
user1500727
10
votes
1 answer

Django - Custom Filter to check if File exists

I made this custom filter to check if an image exists or not: from django import template from django.core.files.storage import default_storage register = template.Library() @register.filter(name='file_exists') def file_exists(filepath): if…
Sourabh
  • 8,243
  • 10
  • 52
  • 98
10
votes
5 answers

How to make uniques in Django Models? And also index a column in Django

This is my simple Django database model. It's for a 5-star rating system. class Rating(models.Model): content = models.OneToOneField(Content, primary_key=True) ip = models.CharField(max_length=200, blank=True) rating =…
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
10
votes
1 answer

django custom manager with filter parameter

I would like to add a custom manager which can be called from a template, but does not affect the entire model (e.g. admin views) and which listens to a parameter set in the request (user_profile). The following is what I have so…
szeta
  • 589
  • 1
  • 5
  • 21
10
votes
3 answers

Django JOIN query without foreign key

Is there a way in Django to write a query using the ORM, not raw SQL that allows you to JOIN on another table without there being a foreign key? Looking through the documentation it appears in order for the One to One relationship to work there must…
xXPhenom22Xx
  • 1,265
  • 5
  • 29
  • 63
10
votes
2 answers

Delete related object via OneToOneField

Is there some clever way how to perform delete in this situation? class Bus(models.Model): wheel = OneToOneField(Wheel) class Bike(models.Model): wheel = OneToOneField(Wheel) pedal = OneToOneField(Pedal) class…
ChRapO
  • 327
  • 5
  • 14
10
votes
2 answers

Can't create super user with custom user model in Django 1.5

my goal is to create a custom user model in Django 1.5 # myapp.models.py from django.contrib.auth.models import AbstractBaseUser class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', …
Guillaume Vincent
  • 13,355
  • 13
  • 76
  • 103
10
votes
3 answers

Best practice: Django multilanguage

i'm a beginner with django. (I just completed the tutorial and following this guide http://www.gettingstartedwithdjango.com) I want to make a site with multilingual content, and i would know which is the best practice, at least with the models: Use…
Jiloc
  • 3,338
  • 3
  • 24
  • 38
10
votes
2 answers

Is there an idiomatic way to get_or_create then update an object in Django?

I have a Django model called StaffSettings which contains various configuration options for users in my Django app. Each User has at most one entry in the StaffSettings table. Assume that one setting is default_year_level, and I have code for my…
bryn
  • 1,246
  • 1
  • 13
  • 21
10
votes
5 answers

Django storing mobile number, what field to use?

In my models I need to store a mobile number in the following format 447182716281. What field should I use? Does Django have anything to support this? example mobile = models.IntegerField(max_length=12)
MarkO
  • 775
  • 2
  • 12
  • 25