Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Django中对多对多进行过滤_Python_Django - Fatal编程技术网

Python 在Django中对多对多进行过滤

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

我无法让这个查询返回多个练习对象,即使我在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)
查询是返回最近一次训练的每次训练

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()

顺便说一句,这个相关的名字令人困惑。我推荐
锻炼
或类似的活动,因为您通过
锻炼来管理
锻炼
实例。锻炼_锻炼
,而不是
锻炼
实例。

感谢您的快速回复和推荐