Adding Foreign Key To Django Model

此生再无相见时 提交于 2019-12-23 03:46:11

问题


I was wondering what they best procedures in turning a column from an IntegerField to a Foreign Key. Here are my two models:

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)

and the second one:

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

and finally my django view code:

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)

I want to change the 'workoutid' column in the exercise model to a foreign key that relates to the id field in the workout model. I tried this changing the changing the model field to:

workoutid = models.ForeignKey(workout);

and then add this this order_by statement to the end of all_exercises in my view i.e

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

i get an error saying that:

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

I think it is a problem in my Model code, but i'm not sure possibly it is an issue with the view.

Thanks for the help guys!


回答1:


You are getting the error because workout_ids isn't a list of ids.

A quick and simple fix to your current problem is to use .values_list('id', flat=True) like so:

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

However, I would highly recommend using models.ForeignKey. Here's a simple example to get you started:

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

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

Then you can write the query:

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


来源:https://stackoverflow.com/questions/11641052/adding-foreign-key-to-django-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!