I am new to Django, I am searching a way to create a model in Django based on the instance of another model, but filtered.
I have a table called Person, which has name and role, in my models.py:
class Person(models.Model):
id = models.UUIDField(primary_key=True)
name = models.CharField(max_length=100)
role = models.CharField(max_length=100)
created_on = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'person'
What I want is to be able in my admin.py to call some subclass, which will display only actors (role="actors"):
@admin.register(Actor)
class Actor(admin.ModelAdmin):...
Is it possible? Or do I have to create one more table only with actors?
I know that I can use list_filter = ('role',)
, but this is not what I am searching for, I need actors exclusively.
I see solution as something like this:
class Actor(models.Model):
objects = Person.objects.filter(role='actor')
class Meta:
verbose_name = 'actor'
or
class Actor(Person):
self.objects.filter(role='actor')
class Meta:
verbose_name = 'actor'
That obviousely does not work.
You can use a Proxy model for this:
class ActorManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(role='actors')
class Actor(Person):
objects = ActorManager()
class Meta:
proxy = True
Proxy models are just a proxy of the inherited model (Person here) ie no new table is created. Here we have created a custom manager so that the roles are always filtered. Now just register this model to the admin site. References: Proxy Models , Custom Managers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.