create and add many to many field in django
- In your Django model, define the ManyToManyField:
class ModelName(models.Model):
related_models = models.ManyToManyField(RelatedModel)
- Create and apply a migration to add the ManyToManyField:
python manage.py makemigrations
python manage.py migrate
- Use the ManyToManyField in your code to add related instances:
instance.related_models.add(related_instance)
- To access related instances:
related_instances = instance.related_models.all()