Luis Salvay
Luis Salvay

Reputation: 11

Group ManyToMany in Django admin

I have a model "Company" having many to many relationships with Country and City while country and city have one to many relationship between them. The problem is that when loading an "enterprise" have to select the countries atienede the company and the cities they serve, but the list of cities is very long and also the cities are all mixed without distinguishing what country you are. What I'd like is to group the cities by country.

It is exactly what django-smart-selects, only this plugin does not work in many to many relationships. Someone could help me adapt this plugin to work with many to many relationship or comment me if they think of another alternative.

Thank you very much!

class Company(models.Model):
    name = models.CharField(max_length=255)
    countries = models.ManyToManyField(Country)
    cities = models.ManyToManyField(City)

class Country(models.Model):
    name = models.CharField(max_length=255)

class City(models.Model):
    name = models.CharField(max_length=255)
    country = models.ForeignKey(Country)

Upvotes: 1

Views: 1189

Answers (1)

ger.s.brett
ger.s.brett

Reputation: 3308

Here is a solution how you can solve this in the admin with smart_selects:

Define the through model for your manytomany relationship (company to city). In the through model you define the relationship to the city as GroupedForeignKey. Then you make an inline in the admin for your Conpany with the through model.

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

class City(models.Model):
    name=models.CharField(max_length=50)
    country=models.ForeignKey(Country)

class CCRel(models.Model):
    city= GroupedForeignKey(City, "country")
    company = models.ForeignKey("Company")

class Company(models.Model):
    name=models.CharField(max_length=50)
    country = models.ManyToManyField(Country,through="CCRel")

And the admin.py:

class CInline(admin.TabularInline):
    model = CCRel
class CAdmin(admin.ModelAdmin):
    inlines=[CInline]
admin.site.register(Company,CAdmin)

It should also work with ChainedForeignKey in a similar manner.

You should remove the country field from the Company model as this is redundant.

Upvotes: 1

Related Questions