Skip to content
thesarfo

Note

Registering Models with the Admin

Registering a model with admin.site.register(), and adding a __str__ method and Meta ordering so it displays sensibly.

views 0

The admin site provides a way for us to manage our models in there. To do that, you have to go to the admin.py file inside the app which models you want to manage.

For instance, we go to the “store” app’s admin.py file, and then we import the models and then register it to the admin site. See below

from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Collection) #Collection is the table we wanna register

But note that when you look at how the collections are being displayed in the admin site, you see that it is in a form that you cant make meaning of. That is django admin’s default way of rendering models. To change that into a normal string representation that we can understand, we need to render the __str__ representation of the model class. ie Collection in this case. see below

class Collection(models.Model):
title = models.CharField(max_length=255)
featured_product = models.ForeignKey(
'Product', on_delete=models.SET_NULL, null=True, related_name='+')
def __str__(self) -> str:
return self.title

Now lets say we want to order our Collection being displayed in our admin site by fields. For instance we want to order them by title, we can create a subclass called Meta in our Collection class and specify the ordering. see below

class Collection(models.Model):
title = models.CharField(max_length=255)
featured_product = models.ForeignKey(
'Product', on_delete=models.SET_NULL, null=True, related_name='+')
def __str__(self) -> str:
return self.title
class Meta:
ordering = ['title']