Using Raw ID Fields in Admin
A snippet showing how to use raw_id_fields in Django admin.
# models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=120)
email = models.EmailField(unique=True)
def __str__(self):
return self.name
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
product = models.CharField(max_length=120)
total = models.DecimalField(max_digits=8, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Order #{self.id} - {self.product}"
# admin.py
from django.contrib import admin
from .models import Customer, Order
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display = ('name', 'email')
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ('id', 'customer', 'product', 'total', 'created_at')
raw_id_fields = ('customer',) # use raw ID widget for ForeignKey
Explanation:
-
Use
raw_id_fieldsonForeignKeyorManyToManyFieldto replace dropdowns with an ID + search popup. - Essential when related tables have thousands of rows, which would otherwise make dropdowns unusable.
- Users can search and pick related records via the popup, keeping the admin responsive.
-
Combine with
search_fieldsin the related model's admin for a smooth lookup experience.
- Category Admin
- Total Views 866
- Last Modified 28 November, 2025
- Tags #admin #raw id #fields #customization
Previous snippet
Admin List Pagination
Next snippet