2👍
✅
Some simple improvements
-
Remove the
if rating in all_ratings
, every rating will be in the list of all ratings -
Do the
delete
on the database side
ind.ratings.all().delete()
- 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()
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.
- [Answered ]-Django is unable to load angular chunks
- [Answered ]-Couldn't import django in virtualenv but works when deactivated
- [Answered ]-Passing variable to a django queryset
- [Answered ]-Using network_mode='host' in docker-compose break run: host type networking can't be used with links
- [Answered ]-Get Session Data in Django Forms
Source:stackexchange.com