Database View and Proxy Model
Learn how to display a database view and create proxy models.
We'll cover the following
Displaying a database view
Sometimes you want to display data which comes from a database view and not from a Django model. It is really easy to do that. You just need to declare the model corresponding to the view in your models.py
file but with the specific keyword managed=False
in the class Meta
and tell Django the database table name:
class QuestionSummary(models.Model):
month = models.DateField()
nbQuestionsByMonth = models.IntegerField()
class Meta:
managed = False
db_table = 'app_questionsummary'
Then, you can reference the model in the admin.py
as usual.
admin.site.register(QuestionSummary)
or
@admin.register(QuestionSummary)
class QuestionSummaryAdmin(admin.ModelAdmin):
...
This will not work at the moment, because the referenced table does not exist. But you should know this for when you come across this use case.
Proxying a model
If you want to display a model twice in the Django Admin (for whatever reason), you will not be able to simply add it twice in the admin.py
file. First, you will need to create a proxy in the models.py
file.
class AuthorClone(Author):
class Meta:
proxy=True
verbose_name_plural = "The Authors clone"
Our proxy is abstracting the Author
class. Then, you can create and register it in the admin.py
.
class AuthorCloneAdmin(admin.ModelAdmin):
fieldsets = [
("Author information", {'fields': ['name','createdDate','updatedDate']}),
]
list_display = ('name','createdDate','updatedDate',)
search_fields = ('name',)
admin.site.register(AuthorClone, AuthorCloneAdmin)
Now, if you check our Django admin page, you will see your author’s clone displayed in your list.
Get hands-on with 1400+ tech skills courses.