Home > Mobile >  Display the id of an object in many to many relation in Django admin
Display the id of an object in many to many relation in Django admin

Time:05-20

I have a model(VariationPrice) in my Django app which has many to many relation with other model(Variation). Under Django Admin VariationPrice, one sees the variations field with many Variations inside it. Is it possible to display the Variation id (Variation.id) along with the Variation name in many to many field of django admin?

class VariationPrice(models.Model):
    price = models.IntegerField()
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    variations = models.ManyToManyField(Variation, blank=True)

CodePudding user response:

The name of the M2M object is rendered by it's __str__() method. So the easiest way to achieve this is to simply add the ID to your str method of the Variation model:

class Variation(models.Model):
    ...
    def __str__(self):
        return f"{self.name}-{self.id}"
  • Related