簡體   English   中英

Django:與用戶表的外鍵關系不驗證

[英]Django: Foreign Key relation with User Table does not validate

考慮以下django模型

from django.db import models                                                                                                                             
from django.contrib import auth
class Topic(models.Model):
   user = models.ForeignKey('auth.models.User')                                                                                                          
   name = models.CharField(max_length = NameMaxLength , unique = True)
   version_number = models.IntegerField(default = 0)
   created_at = models.DateTimeField(auto_now_add  = True)
   modified_at = models.DateTimeField(auto_now = True)
   update_frequency = models.IntegerField()

即使在安裝auth_user表之后,此模型也不會驗證。

In [3]: auth.models.User.objects.all()
Out[3]: [<User: admin>]

上面的語句來自django-admin shell

$ python manage.py syncdb
Error: One or more models did not validate:
topic: 'user' has a relation with model auth.models.User, which has either not
been installed or is abstract.

我在ubuntu 11.04上使用django v1.0.4和pinax 0.7.2,帶有sqlite3數據庫

以下問題沒有多大幫助:

from django.db import models                                                                                                                             
from django.contrib.auth.models import User

class Topic(models.Model):
    user = models.ForeignKey(User) 

'auth.User'也會起作用。 它不是Python的庫語法,而是Django ORM的“app.model”語法。 但是,如果您正在拼命嘗試解決循環依賴,那么您應該只將模型作為字符串傳遞。 如果你有一個循環依賴,你的代碼是有效的。

即使我遇到同樣的問題,

錯誤消息很明確:您尚未安裝用戶模型。

Add "django.contrib.auth" to INSTALLED_APPS in your settings.py.

那就是..希望它會解決這個問題,對我來說很好。

我有同樣的錯誤,但在不同的情況下。 我將models.py拆分為兩個文件:

myapp/
    models/
        __init__.py
        foo.py
        bar.py

在foo.py我有兩個模型:

class Foo(models.Model):
    attr1 = ... etc

class FooBar(models.Model):
    other = ... etc
    foo = models.ForeignKey(Foo)

    class Meta():
        app_label = 'foo'

我在Foo模型中解決了添加Meta的問題:

class Foo(models.Model):
    attr1 = ... etc

    class Meta():
        app_label = 'foo'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM