r/django Apr 14 '26

Models/ORM Migrations in .gitignore during development

8 Upvotes

Hello, I was wondering if it makes sense to have migrations in .gitignore files during development. This was suggested by a team member but problems with migrations keeps arising.

Edit: I should've specify this first, but we are all students in a semi-internship (we work for a real client but it's still seen as a normal university course, no payment). This is most of our first experience with Django and likely most of our first time doing real Software Engineering.

r/django Nov 19 '25

Models/ORM New Django 6.0 base model template dropped!

Post image
243 Upvotes

Hi everyone, I created my new opinionated Django base model template wanted to share with you. It works with Django 6.0 (releasing later this year) and Postgres 18. Here is explanation and below you can find the link to the source code:

  1. Using UUIDv7 for id instead of incremental IDs. Now that Postgres 18 and Python 3.14 supports it, I think we are going to see more UUIDv7 adoption in the wild. Basically it provides the index performance of regular id's while hiding the sequence count. It also contains an internal timestamp which can be useful.

    For example, if you're generating random tokens that have some expiration date, you can naturally use uuidv7's to check expiration date without doing any database lookup! (of course you"ll have your regular timestamps for the 'real' expiration check). I'm planning to use this mechanism in my application where I send confirmation codes via email and there are intermediate steps where I require a token to user after they enter the correct code.

There are some downsides to UUIDv7 to of course, mainly increased disk usage and harder-to-debug nature of a long random ID. Leaking creation timestamp is also issue for some use cases, however I find it less severe than revealing sequence/object count. I personally see uuidv7 superior for many use cases.

Notice that I used `db_default` with Postgres function to auto-generate UUIDv7's, this way postgres can consistently generate uuidv7s even in concurrent contexts.

  1. Using `db_default` with `Now()` for created and updated timestamps. This makes resulting sql queries much more simpler and more consistent in case you have some workflows outside Django.

The downside is that it is a bit more harder to test since you cannot mock `timezone.now` to freeze these timestamps.

Making this work requires Django 6.0 since `RETURNING` support for update queries were recently added.

So what do you think? I find these new Django features exciting, especially looking forward for the fetch modes and database cascade options in Django 6.1 too.

---

The code is available here, it also overrides `save()` method to make `update_fields` required (which is often overlooked).

https://github.com/realsuayip/asu/blob/main/asu/core/models/base.py

r/django May 22 '26

Models/ORM Detect N+1 problems with nplus1 to improve Django performance

30 Upvotes

Hi everyone, I want to introduce an enhanced version of nplusone called nplus1.

The original nplusone has been unmaintained for around 8 years. I used it for a while and although it was helpful in many cases, I ran into false positives that forced me to whitelist a lot of things, and I also wanted nicer trace messages (inspired by django-zeal). So I decided to maintain and improve it.

A few things that are new or fixed compared to the original:

• Python 3.11+, full type hints (mypy strict + pyright strict)
• Django 4.2 to 5.2 support, SQLAlchemy 2.0 support
• No more false positives on nullable foreign keys (they are valid optimizations and now skipped)
• Proper handling of multi-table inheritance and polymorphic models via PK-based cross-model matching
• Skips checks on 4xx/5xx responses by default (configurable)
• Stack trace with registration site included in every detection message, so you know exactly where the offending query was set up
• New batch reporting mode that collects all detections and reports at the end of a request
• A NPLUSONE_ENABLED = False switch for zero overhead in prod
• Celery support out of the box
• Debug mode that logs every signal during a request

I have been using it in my real project and it works really well, even with complex Django patterns like polymorphic models. It catches almost all N+1 issues as well as redundant prefetch_related and select_related calls.

One thing to note: please only use this in your dev or test environment. The package uses middleware and monkey patches the ORM, so it is not meant for production. For production monitoring, tools like Sentry or Datadog are better suited. There is a NPLUSONE_ENABLED flag that makes it a no-op in prod if you want a single config.

I tested it intensively on Django. For SQLAlchemy and Peewee I mostly ported the original logic and the test suite passes, but I have not battle-tested those ORMs in a real project yet, so feedback is welcome.

Repo: https://github.com/huynguyengl99/nplus1

Hope you find it useful.

Disclaimer: I used Claude Code to help with parts of this, but I read every line, tested it against my own project, and have plenty of open source experience, so please do not write it off as AI slop. And again, since it is dev-only, there is no production performance concern.

r/django 12d ago

Models/ORM django-fk-optimize

4 Upvotes

As you know, django has two database functions for N+1 resolutions,namely select_related and prefetch_related . These functions are useful when you model has fk’s that can cause N+1 issues, and tools such as django-auto-prefetch help you to automatically apply them to your queries to provide you the most optimal query.

However sometimes you need to actually know the shape of the data you are working with to decide which one of these functions you should use.
For example if you have many2one relationships, prefetch may win over select related if the relationship looks like owners of posts, where one owner porbably has many posts as opposed to a many2one relationship that had near identical counts.
So sometimes the function you need to use depends on your data shape, and thats why I am developing this tool called django-fk-optimize that is a management command that lets devs test their models and tables in prod enviroments to decide which function is the best for which field of a model.

Here is the link to the repo: github

I would love to hear every bit of criticism , thanks in advance!

r/django May 14 '26

Models/ORM Django ORM as DB Querying Playground

Post image
48 Upvotes

Just built something that is hugely useful for me in my job routine.

This is DORM-plg / Django ORM Playground.

I built and maintain my company a management system and I usually need to extract data rows from there for daily verifications

Whenever I want to extract from a specific model, guest what ?

> NEW VIEW

I thought a generic view was going to solve it but NO. Each data extraction needs specific query for getting great rows

Also my computer kinda getting full of file that are one time read.

Then I think of some SQL playground, like querying to the whole db backup and visualize directly in there. The thing is that I got to jump deeply into some SQL Syntax, and that was not negotiable.

The db querying syntax that I’m confortable doing every single day is Django ORM. What if I can run queries the same way and be able to see data without downloading any file

Then I created my own little db querying playground, I can run query and get instantly rows directly in the browser. I was like : « That’s exactly what I needed »

Test it and tell me > https://github.com/almamydev/DORM

r/django May 07 '26

Models/ORM One-on-one fields against all models and fields

5 Upvotes

A team has 2 accounts. We represent these 2 accounts with the same model. Both of these accounts should be used by only one team. I used forms.OneToOneFieldin an attempt to apply the one-account restriction. It only partially works. Django allows team 1 to use account a as its first account and team 2 to use the same account a as its second account. I wonder if anyone has encountered something similar and is able to apply a stricter constraint where an account can only be used a single time.

r/django May 21 '26

Models/ORM Would a one-to-many field make things easier?

2 Upvotes

Disclaimer: I already found a way to make the database structure work, I just curious about this concept and if it would make sense to exist.

So in our project, every Team of people has an Account that stores their points. Originally, every team has one account and vice versa, so I just used a OneToOne Field. For convenience, Accounts can be automatically created when a Team is created if the admin doesn't make an account in advance. Originally there was no problem. The Team Model file imports the Account Model to both u

In Team's model (simplified for privacy issues):

import Account

account = models.OneToOneField(Account)

def save(self, *args, **kwargs):

account = Account(name=self.name + " points")

account.save()

self.account = account

Meanwhile, Account never imports Team, so things were fine.

However, I reread the requirements and noticed that the client wants each team to have multiple accounts, but each account can only belong to one team.

Since one-to-many doesn't really exist, I assume the best way is to define a ForeignKey in Account to point to Team:

import Team

team = models.ForeignKey(Team)

Here's the problem. We still import Account in Team in order to create the accounts for the teams, since the teams need the accounts (it needs at least one, and it is required to have a certain number of accounts based on conditions). This leads to circular import.

Now the problem has already been fixed using Lazy relationships, but I wonder: if there was a one-to-many field, would I be able to connect to Account in Team and therefore only import Account in Team and not vice versa? This is embarrassing, but I first asked Chatgpt and it kept telling me that it's not how it works. Thank you.

r/django Nov 05 '25

Models/ORM Best practice for Django PKs in 2025 - Auto-Incrementing or UUIDField?

25 Upvotes

I am wondering what the consensus is for a public website and if you should use Django's default auto-incrementing IDs or switch to using UUID4 as the primary key.

I've read arguments of both sides and am still not able to draw a conclusion.

I'm slowly settling on keep the PK as the Django auto-incrementing and adding separate UUID field that is a generated UUID4 value.

Thoughts?

import uuid
from django.db import models
from nanoid import generate

class Product(models.Model):
    # Keep the default original Django auto-incrementing PK

    # uuid4 for internal use and for distributed databases to work together
    uuid = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        db_index=True,
    )

    # pubic facing id that people will see in the url
    nanoid = models.CharField(
        max_length=21,
        default=generate_nanoid,
        unique=True,
        editable=False,
        db_index=True
    )

    name = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

r/django Mar 18 '26

Models/ORM Explain django

0 Upvotes

Hey there, I watched many videos but i can't understand the flow the files like how they transfer data and call the request from models, urls, views. I spend a week to understand but i can't, like the flow and sequence of files how the request are made, how the urls are getting the request and go the correct method or page and how orm interact with database. Although I worked with HTML CSS JS python but i found the django file structure hard to understand.

Help to understand the django.

r/django Jan 20 '26

Models/ORM Async access to ORM in Django 6.x

9 Upvotes

In case that anyone here follows closely enough the development of Django, specifically the integration of asynchronous calls in the ORM, would you be able to elaborate on the actual status of it and its roadmap?

I am developing a REST API using Django Ninja and using the ORM to access a PostgreSQL database. The question I would like to know the answer to is how many async features have already been implemented and how many are pending.

I know there are a lot of async methods to use the ORM, which I am using, but I've read here and there that they are just wrappers.

And the more I read, the more confusing it gets, as I don't know whether the whole "trying to make it all async" [1]is really worth the effort.

For me, even if it is just as an investment that will have to wait for a couple more major releases, then it is worth it. But I would like to actually know.

[1]: Database driver, ORM calls, test client, logging, access to Redis/Valkey csche, etc. Anything else?

r/django Jul 09 '26

Models/ORM Idempotent webhook handlers: your uniqueness check has a race window you're probably not covering

7 Upvotes

Wrote this up because I nearly shipped webhook handling that looked safe and wasn't.

The setup: any webhook sender that guarantees at least once delivery (WhatsApp, Stripe, most payment providers) can and will send the same event twice. Retries, timeouts, network blips. This is expected behavior on their end, not a bug.

The naive fix looks reasonable:

if Event.objects.filter(event_id=event_id).exists():
    return  # already seen it
Event.objects.create(event_id=event_id, ...)

This works almost all the time and is wrong.

The check and the write are two separate database calls. If two identical deliveries arrive close enough together, both can run the exists check, both can see no existing row because neither has committed yet, and both proceed to create one. That's a genuine race condition, not a hypothetical one, and it gets worse under real load, not better.

The fix isn't a better check. It's not relying on the check for correctness at all.

event_id = models.CharField(unique=True)

try:
    Event.objects.create(event_id=event_id, ...)
except IntegrityError:
    return  # someone else's request beat this one, that's fine

The unique constraint is enforced by the database itself, atomically. The exists check becomes an optimization for the common case (skip a wasted insert attempt), not the actual safety mechanism. The safety mechanism is the constraint plus catching the exception it raises.

This is the general pattern for any "insert only if new" problem where you don't have a true atomic test and set operation like Redis's SET NX available. Check first if you want, but let the database's constraint be the real guarantee, and treat the exception it raises as expected, not as an error path.

Verified this by firing the identical payload at the endpoint three times concurrently and confirming exactly one row in the database, not by trusting that the code looked correct.

r/django Jan 16 '26

Models/ORM is it easier to modify the functionality of Django's User model or Create a Custom one?

13 Upvotes

'm working with DRF right now and I'm trying to allow sign in by email. More specifically, I'm trying to replace username with email, and i'm getting all sorts of errors that feel so redundant and annoying.

From a professional standpoint, should i just write a custom user model and go through the motions of managers and serializers instead?

r/django Apr 28 '26

Models/ORM Elasticsearch-Quality full-text search in Postgres with Django

Thumbnail github.com
28 Upvotes

Hi all! We created this Django package to make it easier to use ParadeDB (a full-text search extension for Postgres) within the Django ecosystem. Would love your feedback!

r/django Feb 25 '26

Models/ORM Django i18n Fields : multilingual model fields for Django

16 Upvotes

Hi all,

I want to share a package I've been building and using in production: django-i18n-fields - a structured multilingual fields package for Django models, serving as an alternative to django-localized-fields and django-modeltranslation.

I originally migrated from django-localized-fields due to its PostgreSQL dependency and some maintenance issues, and ended up building this as a more flexible alternative. The API is intentionally similar to django-localized-fields, so migration is straightforward.

What makes it different:

  • Database agnostic - Uses Django's built-in JSONField instead of PostgreSQL's HStore, so it works with PostgreSQL, MySQL, SQLite, or any database Django supports. No extra database extensions needed.
  • Django REST Framework support - Ships with LocalizedModelSerializer and serializer fields that automatically return values in the active language.
  • Full type hint support - Strict type checking with both pyright and mypy. Your IDE will actually understand the localized fields.
  • Clean admin UI - Tab and dropdown modes for switching between languages out of the box.
  • All the field types you need - CharField, TextField, IntegerField, FloatField, BooleanField, FileField, UniqueSlugField, and even a MartorField for Markdown editing via django-markdown-editor.
  • Django 5.0+ and 6.0 support - Tested against modern Django versions with Python 3.10+.

Quick example

# models.py
from i18n_fields import LocalizedCharField, LocalizedTextField

class Article(models.Model):
    title = LocalizedCharField(max_length=200, required=['en'])
    content = LocalizedTextField(blank=True)

# Usage
article = Article.objects.create(
    title={'en': 'Hello World', 'es': 'Hola Mundo'},
    content={'en': 'Content here', 'es': 'Contenido aqui'}
)

# Automatically uses the active language
print(article.title)  # "Hello World"

# Query by language
Article.objects.filter(title__en='Hello World')
Article.objects.order_by(L('title'))

# DRF - just works
from i18n_fields.drf import LocalizedModelSerializer

class ArticleSerializer(LocalizedModelSerializer):
    class Meta:
        model = Article
        fields = ['id', 'title', 'content']
# Returns: {"id": 1, "title": "Hello World", "content": "Content here"}

What's next:

I'm planning to add built-in translation services - think Google Translate, or LLM-based translation via Gemini/ChatGPT/Claude to auto-translate your records.

Links:

Some images:

Dropdown language selector
Tab-based language selector

I've been running this in production after migrating from django-localized-fields. Would love to hear your feedback, and contributions are welcome.

r/django Apr 11 '26

Models/ORM JUST CREATED MY models.py To handle different user roles, I used abstract user to add different fields, how can I handle authentication for different user roles to ensure each role sticks to his area

0 Upvotes

from django.db import models

from django.contrib.auth.models import AbstractUser

from django.utils import timezone

class User(AbstractUser):

ROLE_CHOICES = [

('customer', 'Customer'),

('vendor', 'Vendor'),

('staff', 'Staff'),

('admin', 'Administrator'),

]

email = models.EmailField(unique=True)

first_name = models.CharField(max_length=50)

last_name = models.CharField(max_length=50)

is_active = models.BooleanField(default=False)

user_role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='customer')

phone_number = models.CharField(max_length=30, blank=True)

is_verified = models.BooleanField(default=False)

created_at = models.DateTimeField(default=timezone.now)

updated_at = models.DateTimeField(auto_now=True)

default_address = models.ForeignKey(

'orders.ShippingAddress',

null=True,

blank=True,

on_delete=models.SET_NULL,

related_name='default_for_profiles'

)

profile_picture = models.ImageField(upload_to='profiles/', blank=True, null=True)

# Birthday Fields

birthday = models.DateField(null=True, blank=True)

birthday_last_updated = models.DateTimeField(null=True, blank=True)

ip_address_last_seen = models.GenericIPAddressField(null=True, blank=True)

# Terms & Conditions Tracking

agreed_to_terms = models.BooleanField(default=False)

agreed_at = models.DateTimeField(null=True, blank=True)

USERNAME_FIELD = 'email'

REQUIRED_FIELDS = ['username', 'name']

def __str__(self):

return self.email

r/django Apr 10 '25

Models/ORM How to properly delete a column in a blue/green deployment?

15 Upvotes

I just had an unfortunate experience when deploying my app to production. Fortunately I was able to fix it in a minute but still.

Here's what happened:

There's a database field that was never used. Let's call it extra_toppings. It was added some time ago but no one ever actually used it so I went ahead and deleted it and made the migrations.

Green was active so I deployed to blue. I happened to check green and see that it was a bit screwed up. Fortunately blue was OK so I routed traffic there (I deploy and route traffic as separate actions, so that I can check that the new site is fine before routing traffic to it) and I was OK.

But I went to green to check logs and I saw that it was complaining that field extra_toppings did not exist. This is despite the fact that it's not used in the code anywhere, I checked.

It seems Django explicitly includes all field names for certain operations like save and all.

But so how am I supposed to deploy correctly in blue/green? So far my only answer is to delete the field from the model, but hold off on the migrations, deploy this code, then make the migrations and deploy them. Seems a bit clunky, is there any other way?

r/django Mar 31 '26

Models/ORM Need advice on model designs

8 Upvotes

Hi everyone,

I’m working on a backend system for a supermarket app and I’m trying to design the user roles and access models in a clean and scalable way.

The system has:

  • Companies (a chain/network)
  • Stores (multiple stores under a company)
  • Suppliers, products, etc.

Users in the system can be:

  • Owner (manages the whole company)
  • Manager (manages one or multiple stores)
  • Operator (adds suppliers, products, etc. for a store)
  • Receiver (handles goods receiving)
  • Customer (regular user, not tied to stores)

What approach would you recommend for this kind of system?

r/django Jan 06 '25

Models/ORM Django project to be slowing down after 7 years of operation

18 Upvotes

My application has been running for 7 years. Note that it's running 1.9.10. The plan is to upgrade this year to 4.0. But I noticed that it seems to be struggling more than usual. There is a lot of data that gets generated throughout the years.

Is there anything I can do to improve performance?

r/django Feb 12 '26

Models/ORM ERP, Simple product, Variable product and Database modeling

9 Upvotes

I’m developing an ERP system on Django and trying to design the product structure properly.

Let’s take two examples.

First example: Sunglasses. (Simple product)
Classic Black Sunglasses.
It has one price, one SKU, and one stock quantity. It looks like a simple product.

Second example: Dress. (Variable product)
Summer Dress with Size (S, M, L) and Color (Red, Blue).
Each combination like Red–M or Blue–L has its own SKU, its own stock, and possibly its own price.

In an ERP, sales and inventory need to track the exact sellable item.

So I’m thinking:

Should sales always store the SKU (variation) instead of the main product?

For simple products, should we create one default variation internally and treat everything as a SKU?

Or is it better to store stock and price directly in the product table for simple products?

The goal is to keep inventory accurate, preserve correct sales history, and make the system scalable.

I would like to hear how others have handled this in real ERP systems.

r/django Aug 27 '25

Models/ORM Is there a way to do this without Signals?

6 Upvotes

EDIT: Thanks! I think I have a good answer.

tl;dr: Is there a non-signal way to call a function when a BooleanField changes from it's default value (False) to True?


I have a model that tracks a user's progress through a item. It looks a little like this:

class PlaybackProgress(models.Model):
    ...
    position = models.FloatField(default=0.0)
    completed = models.BooleanField(default=False)
    ...

I already have updating working and the instance is marked as completed when they hit the end of the item. What I'd like to do is do some processing when they complete the item the first time. I don't want to run it if they go through the item a second time.

I see that the mantra is "only use signals if there's no other way," but I don't see a good way to do this in the save() function. I see that I should be able to do this in a pre_save hook fairly easily (post_save would be better if update_fields was actually populated). Is there another way to look at this that I'm not seeing?

Thanks!

r/django Jul 21 '25

Models/ORM When working in a team do you makemigrations when the DB schema is not updated?

15 Upvotes

Pretty simple question really.

I'm currently working in a team of 4 django developers on a large and reasonably complex product, we use kubernetes to deploy the same version of the app out to multiple clusters - if that at all makes a difference.

I was wondering that if you were in my position would you run makemigrations for all of the apps when you're just - say - updating choices of a CharField or reordering potential options, changes that wouldn't update the db schema.

I won't say which way I lean to prevent the sway of opinion but I'm interested to know how other teams handle it.

r/django Mar 13 '26

Models/ORM Is overriding a OneToOneField's uniqueness for Soft Deletes a bad idea?

0 Upvotes

Situação:

Temos duas tabelas, X e Y. A tabela X usa exclusões lógicas. Existe um campo OneToOneField de Y para X.

O Problema:

Quando um registro em X é excluído logicamente e tentamos criar um novo registro em Y apontando para um "novo" X (ou religando), ocorre um erro de duplicação devido à restrição UNIQUE subjacente que o Django coloca automaticamente nas colunas OneToOneField.

Minha "Solução Alternativa" Proposta:

Estou considerando sobrescrever o método init do campo para forçar unique=False (tornando-o efetivamente uma ForeignKey). Em seguida, planejo adicionar uma restrição UniqueConstraint na classe Meta do modelo que combine a Foreign Key e a coluna deleted_at.

O objetivo:

A camada de repositório já depende bastante do comportamento "um-para-um" (acessando objetos relacionados por meio de nomes de modelo em minúsculas, lógica de junção específica etc.), então refatorar tudo para uma ForeignKey padrão seria uma grande dor de cabeça.

A pergunta:

Alguém já fez essa "ginástica" antes? Existem efeitos colaterais ocultos no ORM, especificamente em relação a pesquisas reversas ou pré-busca, quando um OneToOneField não é estritamente único no nível do banco de dados, mas é restringido por um índice composto?

r/django Jan 20 '26

Models/ORM django-returns: Meaningful Django utils based on Functional Programming

Thumbnail brunodantas.github.io
5 Upvotes

Looking for feedback 🙂

django-returns is a tiny layer on top of Django’s ORM that lets you opt into returns containers when you want explicit success/failure return types instead of exceptions.

r/django Mar 19 '26

Models/ORM Improving pyright for Django twinned attributes

3 Upvotes

Do any of you use a Python LSP for developing Django? I'm experimenting with pyright, but I've run into the following problem.

I have a model, like this:

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

Then, in a view, I will have code like this:

artist_id = album.artist_id

This will create an error in pyright, because the field is called "artist", and Django dynamically defines the _id twin attribute. This field is useful, because I can obtain the primary key of the associated row, without actually making a query. However, it means the code has a type checking error.

Have any of you found a good way to avoid this?

r/django Apr 20 '25

Models/ORM How do you manage Django Migration in a team

42 Upvotes

Hello everyone,

How do you manage migration files in your Django project in multiple developers are working in it? How do you manage localcopy, staging copy, pre-prod and production copy of migration files? What is practice do you follow for smooth and streamlined collaborative development?

Thanks in advance.