2012-04-24 19 views
1

私のmodels.pyファイルのForeignKeyのパラメータとしてUserモデルを渡そうとしていますが、エラーTypeError: int() argument must be a string or a number, not 'User'が発生しています。ここでDjangoでForeignKeyをユーザに渡す際のエラー

が私のファイルです、私が間違ってやっているものを私に教えてください:位置引数を使用して

models.py

from django.db import models 

class Lesson(models.Model): 
    name = models.CharField(max_length=30) 
    author = models.ForeignKey('auth.User') 
    description = models.CharField(max_length=100) 
    yt_id = models.CharField(max_length=12) 
    upvotes = models.IntegerField() 
    downvotes = models.IntegerField() 
    category = models.ForeignKey('categories.Category') 
    views = models.IntegerField() 
    favorited = models.IntegerField() 

    def __unicode__(self): 
     return self.name 

populate_db.py

from django.contrib.auth.models import User 
from edu.lessons.models import Lesson 
from edu.categories.models import Category 

users = User.objects.all() 

cat1 = Category(1, 'Mathematics', None, 0) 
cat1.save() 
categories = Category.objects.all() 

lesson1 = Lesson(1, 'Introduction to Limits', users[0], 'Introduction to Limits', 'riXcZT2ICjA', 0, 0, categories[0], 0, 0) 
lesson1.save() # Error occurs here 
+0

それは、それをインポートする –

答えて

1

ここでは非常に混乱しており、原因と思われます。

自分のモデルのForeignKeyに位置指定引数を使用してエラーを再現できます。 kwargsを使うと問題は解決します。

私はなぜに探しでも、興味がない - 私はモデルを投入するために混乱位置引数を使用したことがない(あなたがあなたのモデルを変更した場合、彼らは混乱したメッセージで、あまりにもすべての時間を破るように思える)

編集:またははるかに悪いことに、間違ったモデルフィールドに入力フィールドが移動している間に、サイレントエラーが発生する。 django.contrib.authインポートユーザーから

0

は(正確な輸入コールを忘れてしまった) 著者= models.ForeignKey(ユーザー)

編集(追加):私は、私が述べた方法でユーザーをインポートして使用することになり「著者.category 'は他の関係に使用されます。これは私よりもDjangoについてもっと知っている人たちによって解決されています。

+0

彼の方法は、ヘッドの – BenH

+0

@BenH感謝有効アップする必要があります。..私のポストにあります。私は前にそのように呼んだことはありません。他のものは、kw引数の使用とデフォルト値の受け渡しについては正しいです。私はかつて音楽ディスコグラフィーサイトのモデルをやろうとしていましたが、m2mの関係がたくさんありました。答えはmodels.ManyToManyField(Vocalists)の代わりにmodels.ManyToManyField( 'Vocalists')を使用するように、別のモデルで入力する前にm2mモデルを定義する必要がありました。初心者の間違いは、私が解釈した言語の特徴については考えていない。 – eusid

0

キーワード引数を使用するだけでなく、デフォルトのフィールド値を使用して初期化するだけで済みます。

class Lesson(models.Model): 
    name = models.CharField(max_length=30) 
    author = models.ForeignKey('auth.User') 
    description = models.CharField(max_length=100) 
    yt_id = models.CharField(max_length=12) 
    upvotes = models.IntegerField(default=0) 
    downvotes = models.IntegerField(default=0) 
    category = models.ForeignKey('categories.Category') 
    views = models.IntegerField(default=0) 
    favorited = models.IntegerField(default=0) 

    def __unicode__(self): 
     return self.name 


lesson1 = Lesson(name='Introduction to Limits', author=users[0], description='Introduction to Limits', yt_id='riXcZT2ICjA', category=categories[0]) 
lesson1.save() 
関連する問題