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
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.
It should work without __exact
:
exercises = Exercise.objects.filter(workout_exercises=workouts)
But why do you not use the exercises
field directly:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.