Germano Carella
Germano Carella

Reputation: 473

Python django admin: How can I show only items belonging to specific model in an admin page?

I'm learning django for building my website. I learned how to create models, views, but now I have some question relative to admin interface. So I have tis code:

from django.db import models

class AudioBook(models.Model):
    titolo=models.CharField(max_length=250)
    capitoli=models.ManyToManyField('Chapters')

class Chapters(models.Model):
    capitolo=models.CharField(max_length=250)

Now, when I add a new audiobook I can see chapters previously added to others audiobooks. This is bad. I want only the chapters taht belong to this audiobook, so, when I add a new one, the list must be empty.

I tried some things: adding limit_choices_to = models.Q(audiobook__titolo=titolo), but it doesn't work.

In command line I can retrieve these info by adding filters on Chapters object, but I can reproduce this situation in admin interface. Any idea? I searched on google but I didn't find anything that helps me.

Germano

Upvotes: 1

Views: 246

Answers (1)

Ines Tlili
Ines Tlili

Reputation: 810

For ManyToMany relationships, Django admin interface allows you to see the entire list of choices you have and then you select whichever you want to add to your AudioBook object. It does not mean all of them belong to that audio book. The selected ones (the ones you added to you audio books) will have normally a grey background

here's an example picture

If that interface bothers you that much, I suggest that you add AudioBook foreign key in Chapters instead of your MAnyToMany relationship:

class Chapters(models.Model):
    capitolo=models.CharField(max_length=250)
    audio_book = models.ForeignKey(AudioBook,on_delete=models.CASCADE)

It's more relevent in your case. You still can access the audio book's chapters as easily.

Upvotes: 1

Related Questions