2

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.

MStikh
  • 368
  • 4
  • 21

1 Answers1

2

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

Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
  • I know need to understand how to use this model as a field in another model, which is connected to original Person through intermediate table, if i just use `actors = models.ManyToManyField('Actor', through=FilmWorkPerson)` I get an error (does not have a foreign key to ). If you want I can make one more separate question to which you can answer :) – MStikh Jan 22 '21 at 19:51
  • Don't make a `ForeignKey` to this model, Make a `ForeignKey` to `Person` – Abdul Aziz Barkat Jan 23 '21 at 05:36
  • but then it will show all persons but not only actors – MStikh Jan 23 '21 at 07:31
  • @MStikh look at this question [filter foreignkey field in django admin](https://stackoverflow.com/questions/10179129/filter-foreignkey-field-in-django-admin). It may help you. – Abdul Aziz Barkat Jan 23 '21 at 07:45
  • Now when I try add new entry to the actors, admin panel does not let me to do it: Film work person with this Movie already exists. – MStikh Jan 23 '21 at 17:40