繁体   English   中英

在Django中进行多对多过滤

[英]Filtering on many to many in 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(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时才返回单个练习。

它应该在没有__exact情况下__exact

exercises = Exercise.objects.filter(workout_exercises=workouts)

但是,为什么不直接使用exercises字段:

workout = Workout.objects.latest('created')  # singular sounds more correct to me
exercises = workout.exercises.all()

顺便说一句,这个相关名称令人困惑。 我建议进行workouts或类似方法,因为您是通过exercise.workout_exercises而不是WorkoutExercise实例来管理Workout实例的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM