MStikh
MStikh

Reputation: 404

How to create a model in Django based on the instance of another model, but filtered

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.

Upvotes: 3

Views: 1677

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21802

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) i.e. 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

Upvotes: 3

Related Questions