我有一个这样的模型:
from django.db import models
from django.contrib.auth.models import User
class Skill(models.Model):
title = models.CharField(max_length=255)
def __unicode__(self):
return self.title
class UserSkills(models.Model):
user = models.ForeignKey(User)
skill = models.ForeignKey(Skill)
def __unicode__(self):
return '%s | %s' % (self.user, self.skill)
当我尝试这样做时:
>>> u = User.objects.get(username='myuser')
>>> s, created = Skill.objects.get_or_create(title='mysql')
>>> type(u)
<class 'django.contrib.auth.models.User'>
>>> type(s)
<class 'django_myapp.models.Skill'>
>>> userskill, created = UserSkills.objects.get_or_create(skill=s, user=u)
TypeError: 'skill' is an invalid keyword argument for this function
我在这里做错了什么?
顺便说一句,我认为我的UserSkills
模型可能是多余的 - 它应该只是ManyToMany
Skill
模型上的User
字段吗?
回溯:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/sam/.envs/rs-open-auth/local/lib/python2.7/site-packages/django/db/models/manager.py", line 149, in create
return self.get_query_set().create(**kwargs)
File "/home/sam/.envs/rs-open-auth/local/lib/python2.7/site-packages/django/db/models/query.py", line 414, in create
obj = self.model(**kwargs)
File "/home/sam/.envs/rs-open-auth/local/lib/python2.7/site-packages/django/db/models/base.py", line 415, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
答案 0 :(得分:0)
致电时:
userskill, created = UserSkills.objects.get_or_create(skill=s, user=u)
“s”以前被定义为'mysql'(“s”是一个字符串)。但是,当创建具有“技能”外键的新模型记录时,“技能”必须是主键(即1,2等等)。您可以通过直接调用主键来完成此操作(例如,您刚刚创建的“技能”是技能模型中的第一个技能:
userskill, created = UserSkills.objects.get_or_create(skill=1, user=u)
或者你可以调用“s”的主键来创建新的UserSkills实例:
userskill, created = UserSkills.objects.get_or_create(skill=s.pk, user=u)