Wednesday, June 13, 2018

Add a unique “intermediary” model to all my Django ManyToManyField()

Leave a Comment

Hello Awesome People!

Such a question that I have made a lot of searches for it. I am done building a website two(2) months ago, but today The team decides to track every time an instance has been added to a Model in ManyToManyField() fields.

I was thinking using the through argument to point to the model that will act as an intermediary may work but not at all in my case (70%). Just Because I want to have a unique intermediary model that will record for all ManyToManyField()

class Group(models.Model):     name = models.CharField(max_length=128)     members = models.ManyToManyField(Person, through='Membership')  class Membership(models.Model):     person = models.ForeignKey(Person, on_delete=models.CASCADE)     group = models.ForeignKey(Group, on_delete=models.CASCADE)     date_joined = models.DateTimeField(auto_now_add=True) 

Ah! Something is required. I need to explicitly specify foreign keys to the models that are involved in the many-to-many relationship.

Django ContentType may anticipate for all my models, but it's not working, I wonder why? it also contains ForeignKey (the one required by an intermediary model).

Do I really need to edit all my ManyToManyField fields and create Model as much as ManytoManyField? is there a way to record date_joined without creating an intermediary model for each?

1 Answers

Answers 1

Are you perhaps looking for something like django admin's LogEntry model? LogEntry contains the ContentType of the model instance that has changed, the id of the instance, the type of change and an abstract change message. With all of that you can retrace changes made to instances.
In django admin, the views take care of adding records to LogEntry via three methods log_change/addition/deletion: click.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment