Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Large ManyToMany relations on django admin form

So, I have the following models:

class Band(models.Model):
    name = models.CharField(max_length=50)

class Contract(models.Model):
    band = models.ForeignKey(Band)
    when = models.DateTimeField(auto_now_add=True)
    salary = models.IntegerField()

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)
    bands = models.ManyToManyField(Band, through=Contract)

class Album(models.Model):
    artist = models.ForeignKey(Musician)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

So, I wanted to expose that on the admin page. So far, so good.

Note that our musicians here keep jumping in and out from bands. Some say one of them even had been on over 2 millions bands in his life-time. I don't know, maybe the bands are Whitesnake, Metallica or something.

How should we do that on the Django Admin Page?

I tried using raw_id_fields and apart the fact I didn't like the effect, it didn't work so well. It took a lot of time to load and it didn't let me add more ids. Weird.

I've used admin.StackedInline with no luck cause it will try to load every contract in a which, well, it's gonna take only 2 thousand years.

When Musician had a direct relation to Band it worked just fine with this library. But now that the relation isn't an straight one. Looks like autocomplete doesn't support it(it was getting slow anyway).

So, with all of this, I ask you lord SO members. What's the best way to do this? Is it autocomplete? Someone must have had to come across this issue!

Thanks in advance.

like image 852
Patrick Bassut Avatar asked Nov 21 '22 03:11

Patrick Bassut


1 Answers

To avoid loading every bands in your admin page use autocomplete_fields Django doc.
Just use it like that in your admin.py.

autocomplete_fields = ('bands',)

Then no bands will be pulled from DB to front, but you will be able to select it through a Select2 search field and it will be printed as "tags".

like image 135
VivienG Avatar answered Dec 29 '22 02:12

VivienG