Python 在Django中对多对多进行过滤
我无法让这个查询返回多个练习对象,即使我在sql中使用生成的查询,它也会像我预期的那样返回两个练习Python 在Django中对多对多进行过滤,python,django,Python,Django,我无法让这个查询返回多个练习对象,即使我在sql中使用生成的查询,它也会像我预期的那样返回两个练习 class Workout(models.Model): created = models.DateTimeField(auto_now_add=True) workout_type = models.ForeignKey(WorkoutType, on_delete=models.CASCADE) exercises = models.ManyToManyField(Ex
class Workout(models.Model):
created = models.DateTimeField(auto_now_add=True)
workout_type = models.ForeignKey(WorkoutType, on_delete=models.CASCADE)
exercises = models.ManyToManyField(Exercise, through=u'WorkoutExercise', related_name=u'workout_exercises')
class WorkoutExercise(models.Model):
exercise = models.ForeignKey(Exercise)
workout = models.ForeignKey(Workout)
class Exercise(models.Model):
name = models.CharField(max_length=255, unique=True)
查询是返回最近一次训练的每次训练
workouts = Workout.objects.latest('created')
exercises = Exercise.objects.filter(workout_exercises__exact=workouts)
如上所述,当它生成的查询在sql中应该并且确实返回2时,这只返回一个练习。它应该在不使用
\uuu-exact
的情况下工作:
exercises = Exercise.objects.filter(workout_exercises=workouts)
但是为什么不直接使用练习
字段:
workout = Workout.objects.latest('created') # singular sounds more correct to me
exercises = workout.exercises.all()
顺便说一句,这个相关的名字令人困惑。我推荐
锻炼
或类似的活动,因为您通过锻炼来管理锻炼
实例。锻炼_锻炼
,而不是锻炼
实例。感谢您的快速回复和推荐