Joer
Joer

Reputation: 73

ManyToManyField in Django with addinational information

I'm trying to figure out how to add additional information with a ManyToManyField in Django. For example this code:

class Animal(models.Model):
    # ...
    pass

class Log(models.Model):
    animal = models.ManyToManyField(Animal)

If I would like to create a Log object and select the Animal object to it. Then I want to include more information in my Log like color of hair, colors of eyes with the Animal object there (I can't add those inside the Animal object itself).

And then I want to add another exactly the same object again to the Log object. For example a fox. So I want to add the Animal object twice for two different foxes to the log. The characteristics are the same but the only thing is some slight change in the hair color. How could this be accomplished?

Upvotes: 0

Views: 99

Answers (2)

Phoenix
Phoenix

Reputation: 4274

django by default create a third model to handle manyTomany relationship, you can override this model and add your custom fields into it by useing through, as doc said use it like below code:

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    date_joined = models.DateField()
   invite_reason = models.CharField(max_length=64)

Upvotes: 2

Kryštof Řeháček
Kryštof Řeháček

Reputation: 2483

If you want to use m2m field, you can specify through model which will be between the models and can carry additional information, example here (https://gist.github.com/jacobian/827937). Some custom functionality can be done using signals that provides through model. It can be accessed with Log.animal.through.

But your design is i think bad. Better would be having foreign key with no reverse relation on Log and adding signal to post save which will on create created instance of Log and added information to it and set fk to the created instance of animal. https://docs.djangoproject.com/en/2.1/topics/signals/#listening-to-signals

Upvotes: 1

Related Questions