简体   繁体   中英

Django rest-api - attributeerror: 'str' object has no attribute '_meta'

I'm getting the following error while running manage.py migrate in my Django rest-api. I'm unable to pinpoint where to look. Help appreciated.

attributeerror: 'str' object has no attribute '_meta'

The traceback shows the following:

'' Traceback (most recent call last): File "/home/myproject/myproject-api/manage.py", line 25, in execute_from_command_line(sys.argv)

File "/home/myEnv/lib/python3.9/site-packages/django/core/management/ init .py", line 419, in execute_from_command_line utility.execute()

File "/home/myEnv/lib/python3.9/site-packages/django/core/management/ init .py", line 395, in execute django.setup()

File "/home/myEnv/lib/python3.9/site-packages/django/ init .py", line 24, in setup apps.populate(settings.INSTALLED_APPS)

File "/home/myEnv/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready()

File "/home/myEnv/lib/python3.9/site-packages/cacheops/ init .py", line 18, in ready install_cacheops()

File "/home/myEnv/lib/python3.9/site-packages/funcy/flow.py", line 231, in wrapper return func(*args, **kwargs)

File "/home/myEnv/lib/python3.9/site-packages/cacheops/query.py", line 578, in install_cacheops opts = rel.through._meta AttributeError: 'str' object has no attribute '_meta'

''

The issue was this. I had to install

pip install django-cacheops==0.9.3

This should be helpful for anyone who encounters the exact above error.

The error you get from cacheops seems to have to do with the fact that you're using a many-to-many relationship with a through model, where you specify the through model by passing a string with the class's name instead of the class itself, because the class is only defined below. Although this is perfectly common practice, cacheops seems to require that you do it differently:

Namely, try to reference your through model by passing the class instead of a string with the class's name. For this, you need to reorder your code a bit, putting the class definition of your through model first, which of course requires you to pass strings instead of classes to ForeignKey there. Eg do it like this:

class PostCategory(models.Model):
    post = models.ForeignKey('Post')
    category = models.ForeignKey('Category')

class Post(models.Model):
    pass

class Category(models.Model):
    posts = models.ManyToManyField(Post, through=PostCategory, related_name='categories')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM