0

我有一个这样的模型:

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吗?SkillUser

编辑

追溯:

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])
4

1 回答 1

0

你打电话时:

userskill, created = UserSkills.objects.get_or_create(skill=s, user=u)

“s”以前定义为“mysql”(“s”是一个字符串)。但是,在创建具有“skill”外键的新模型记录时,“skill”必须是主键(即 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)
于 2013-10-04T17:40:31.853 回答