Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 281
MStikh Avatar asked Nov 20 '25 00:11

MStikh


1 Answers

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

like image 179
Abdul Aziz Barkat Avatar answered Nov 21 '25 13:11

Abdul Aziz Barkat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!