[英]Filtering on many to many in Django
i can't get this query to return more than one exercise object, even though if i use the generated query in sql it returns both exercises as i expect 我无法获得此查询以返回多个练习对象,即使我在sql中使用生成的查询,它也按预期返回了两个练习
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)
And the query is to return every exercise for the latest workout 查询是返回每次锻炼以进行最新锻炼
workouts = Workout.objects.latest('created')
exercises = Exercise.objects.filter(workout_exercises__exact=workouts)
As stated, this only returns a single exercise when the query it generates should and does return 2 in sql. 如前所述,这仅在它生成的查询应且在sql中返回2时才返回单个练习。
It should work without __exact
: 它应该在没有__exact
情况下__exact
:
exercises = Exercise.objects.filter(workout_exercises=workouts)
But why do you not use the exercises
field directly: 但是,为什么不直接使用exercises
字段:
workout = Workout.objects.latest('created') # singular sounds more correct to me
exercises = workout.exercises.all()
BTW, that related name is confusing. 顺便说一句,这个相关名称令人困惑。 I'd recommend workouts
, or the like, since you are managing Workout
instances via exercise.workout_exercises
, not WorkoutExercise
instances. 我建议进行workouts
或类似方法,因为您是通过exercise.workout_exercises
而不是WorkoutExercise
实例来管理Workout
实例的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.