将外键添加到Django模型

时间:2012-07-25 00:12:59

标签: python django django-models django-views

我想知道他们在将一个列从IntegerField转换为外键时的最佳程序。这是我的两个模型:

class workout(models.Model):

    userid = models.IntegerField()
    datesubmitted = models.DateField()
    workoutdate = models.DateField(); 
    bodyweight = models.FloatField(null=True);
    totalreps = models.IntegerField() 
    totalweight = models.FloatField()
    numsets = models.IntegerField(); 
    numexercises = models.IntegerField()
    workoutname = models.CharField(max_length=250)

和第二个:

class exercise(models.Model):  
    userid = models.IntegerField();
    workoutid = models.IntegerField(); 
    exercisename = models.CharField(max_length = 100)
    repetitions = models.IntegerField()
    weight = models.FloatField()

最后我的django查看代码:

user =User.objects.get(username = request.session['username']) #user 
        dates = request.GET.getlist('datepickerfilter') # two dates
        workout_ids = workout.objects.filter(userid=user.id).filter( workoutdate__gte = dates[0]).filter(workoutdate__lte = dates[1])
        all_exercises = exercise.objects.filter(workoutid__in = workout_ids)

我想将练习模型中的“workoutid”列更改为与锻炼模型中的id字段相关的外键。我尝试将更改模型字段更改为:

workoutid = models.ForeignKey(workout);

然后在我的视图中将此order_by语句添加到all_exercises的末尾,即

all_exercises = exercise.objects.filter(workoutid__in = workout_ids).order_by("workoutid__workoutdate")

我得到一个错误说:

(1054, "Unknown column 'tracking_exercise.workoutid_id' in 'field list'")

我认为这是我的模型代码中的一个问题,但我不确定它是否与视图有关。

感谢帮帮!

1 个答案:

答案 0 :(得分:1)

您收到错误,因为workout_ids不是ID列表。

对当前问题的快速而简单的解决方法是使用.values_list('id', flat=True),如下所示:

workout_ids = workout.objects.filter(userid=user.id).\
    filter(workoutdate__gte=dates[0]).\
    filter(workoutdate__lte=dates[1]).\
    values_list('id', flat=True)

但是,我强烈建议您使用models.ForeignKey。这是一个让你入门的简单例子:

class Workout:
    user = models.ForeignKey(User)
    # other fields go here...

class Exercise:
    workout = models.ForeignKey(Workout)
    # other fields go here...

然后你可以编写查询:

workout_list = Workout.objects.filter(user=request.user)
exercise_list = Exercise.objects.filter(workout__in=workout_list).order_by('workout__workoutdate')