开发者

Django: Foreign Key relation with User Table does not validate

开发者 https://www.devze.com 2023-04-02 11:48 出处:网络
Consider the following django model from django.db import models from django.contrib import auth class Topic(models.Model):

Consider the following django model

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()

This model does not validate even after installing the auth_user table.

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

The above stat开发者_开发知识库ement is from 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.

I am using django v1.0.4 with pinax 0.7.2 on ubuntu 11.04 , with sqlite3 database

The following Questions did not help much:

  • Foreign key to User table in django
  • How do I create a foreign key to the User table in Django?


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

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

'auth.User' would have worked, too. It's not Python's library syntax, it's the Django ORM's "app.model" syntax. But you should only pass the model as a string if you're desperately trying to solve a circular dependency. And if you have a circular dependency, your code is eff'd.


Even I faced same issue,

The error message is clear: you haven't installed the User model.

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

That all..Hope it will solve this issue, worked fine for me.


I had the same error, but in different situation. I splitted the models.py in two files:

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

In foo.py I had two models:

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

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

    class Meta():
        app_label = 'foo'

I solved adding Meta also in Foo model:

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

    class Meta():
        app_label = 'foo'
0

精彩评论

暂无评论...
验证码 换一张
取 消