Skip to content

Commit

Permalink
Added database vieww chapter
Browse files Browse the repository at this point in the history
  • Loading branch information
shabda committed Feb 20, 2018
1 parent f53c3eb commit 12525ff
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 1 deletion.
Binary file added docs/database_view.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
41 changes: 41 additions & 0 deletions docs/database_view.rst
Original file line number Diff line number Diff line change
@@ -1,2 +1,43 @@
How to add a database view to Django admin?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

You have a database view, created as this::

create view entities_entity as
select id, name from entities_hero
union
select 10000+id as id, name from entities_villain


It has all the names from :code:`Hero` and :code:`Villain`. The id for Villain ae set :code:`10000+id as id`
because we don't indent to cross 10000 Heroes::

sqlite> select * from entities_entity;
1|Krishna
2|Vishnu
3|Achilles
4|Thor
5|Zeus
6|Athena
7|Apollo
10001|Ravana
10002|Fenrir

Then you add a :code:`managed=False` model::

class AllEntity(models.Model):
name = models.CharField(max_length=100)

class Meta:
managed = False
db_table = "entities_entity"

And add it to admin.::

@admin.register(AllEntity)
class AllEntiryAdmin(admin.ModelAdmin):
list_display = ("id", "name")

And your admin looks like this

.. image:: database_view.png
7 changes: 6 additions & 1 deletion heroes_and_monsters/entities/admin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.contrib import admin
from django.db.models import Count

from .models import Hero, Villain, Category, Origin, HeroProxy
from .models import Hero, Villain, Category, Origin, HeroProxy, AllEntity

import csv
import sys
Expand Down Expand Up @@ -196,3 +196,8 @@ def villain_count(self, obj):

hero_count.admin_order_field = '_hero_count'
villain_count.admin_order_field = '_villain_count'


@admin.register(AllEntity)
class AllEntiryAdmin(admin.ModelAdmin):
list_display = ("id", "name")
7 changes: 7 additions & 0 deletions heroes_and_monsters/entities/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,10 @@ class Villain(Entity):
)
is_unique = models.BooleanField(default=True)
count = models.PositiveSmallIntegerField(default=1)

class AllEntity(models.Model):
name = models.CharField(max_length=100)

class Meta:
managed = False
db_table = "entities_entity"

0 comments on commit 12525ff

Please sign in to comment.