Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to represent Many to many relationship in django admin

I have a unique problem the way it should be handled in django admin.

I have following models structure...

class Product(models.Model):
    name    = models.CharField(max_length = 100)
    base_price = models.DecimalField(max_digits = 5, decimal_places = 2)


    def __unicode__(self):
        return self.name


class Country(models.Model):
    name = models.CharField(max_length = 2)
    base_price = models.DecimalField(max_digits = 5, decimal_places = 2)    

    def __unicode__(self):
        return self.name


class CountryProduct(models.Model):
    country = models.ForeignKey(Country)
    product = models.ForeignKey(Product)
    overriden_price = models.DecimalField(max_digits = 5, decimal_places = 2)

    class Meta:
        unique_together = (("country", "product"),)

As shown here there is many to many relationship between products and countries.... I want to provide admin interface for overriding base price for given country and product.

One option to have ui as follows, here dash (-) represents default price and value in number represents override price for given country and product.

countries -> | US  | UK 
products     |     |
---------------------------
Product1     |  -  |  10
Product2     |  5  |   7

But I don't know how to do that....

I am open to look at alternative approaches (including changes in model structure) as well as long as it meets the requirement... Your input of any sort will definitely be useful to me...

Thanks in Advance :)

like image 397
Software Enthusiastic Avatar asked Nov 06 '22 16:11

Software Enthusiastic


1 Answers

I got the solution, here is my answer to my question... Let me share it with you... I changed the model in following way....

class Product(models.Model):
    name    = models.CharField(max_length = 100)
    base_price = models.DecimalField(max_digits = 5, decimal_places = 2)


    def __unicode__(self):
        return self.name


class Country(models.Model):
    name = models.CharField(max_length = 2)
    base_price = models.DecimalField(max_digits = 5, decimal_places = 2)    
    products = models.ManyToManyField(Product, through = 'CountryProduct')

    def __unicode__(self):
        return self.name


class CountryProduct(models.Model):
    country = models.ForeignKey(Country)
    product = models.ForeignKey(Product)
    overriden_price = models.DecimalField(max_digits = 5, decimal_places = 2)

    class Meta:
        unique_together = (("country", "product"),)


class CountryProductInline(admin.TabularInline):
    model = CountryProduct

class CountryAdmin(admin.ModelAdmin):
    inlines = [CountryProductInline]

class ProductAdmin(admin.ModelAdmin):
    inlines = [CountryProductInline]

Though this is not the way I expected, this gives me even better solution....

like image 75
Software Enthusiastic Avatar answered Nov 11 '22 03:11

Software Enthusiastic