[Answered ]-Django ManyToManyField delete across models

2👍

Some simple improvements

  1. Remove the if rating in all_ratings, every rating will be in the list of all ratings

  2. Do the delete on the database side

 ind.ratings.all().delete()
  1. Use prefetch_related to get the foreign key objects
self.all_individuals.prefetch_related('ratings'):  

Combined would be:

def destroy(self):
    for ind in self.all_individuals.prefetch_related('ratings'):  
        ratings = ind.ratings.all().delete()
👤Sayse

0👍

I think that in this case using ManyToManyField isn’t the best choice.

You’ll have less problems using common ForeignKey’s changing a little the structure of this models.

Eg.

class Rating(models.Model):
    rater = TextField(null=True)
    rating = FloatField(null=True)
    created = models.DateTimeField(null=True)

    stimulus = models.ForeignKey('Stimulus', related_name='ratings')

class Stimulus(TimeStampedModel):
    genes = TextField()
    weights = ListField()
    #ratings = ManyToManyField(Rating, null=True)
    evaluation = FloatField(null=True)
    complete = BooleanField(default=False)

    experiment = models.ForeignKey('Experiment', related_name='stimulus')

class Experiment(models.Model):
    #all_individuals = ManyToManyField(Stimulus, null=True)
    name = models.CharField(max_length=100)

This is a more clear structure and when you delete Experiment by, experiment_instance.delete() a delete cascade will delete all other related models.

Hope it helps.

Leave a comment