![](/img/trans.png)
[英]AttributeError: module 'django.db.models' has no attribute 'Models'
[英]AttributeError: module 'django.db.models' has no attribute 'get_models'
為什么在調用get_model()
函數時出現問題? 這是我正在嘗試做的事情:
@classmethod
def get_content_models(cls):
"""
Return all Package subclasses.
"""
is_content_model = lambda m: m is not Package and issubclass(m, Package)
return list(filter(is_content_model, models.get_models()))
以前曾經可以使用,但是現在更新到新的Django之后,它會引發錯誤。 如何解決?
更新
下面是我的模特
from django.db import models
class Package(BasePackage):
"""
A package in the package tree. This is the base class that custom content types
need to subclass.
"""
parent = models.ForeignKey("Package", blank=True, null=True, related_name="children", on_delete=models.CASCADE)
titles = models.CharField(editable=False, max_length=1000, null=True)
content_model = models.CharField(editable=False, max_length=50, null=True)
in_menus = MenusField(_("Show in menus"), blank=True, null=True)
login_required = models.BooleanField(_("Login required"), default=False,
help_text=_("If checked, only logged in users can view this Package"))
itinerary = models.ManyToManyField('ItineraryItem', through="PackageItinerary")
def __str__(self):
return self.title
def save(self, *args, **kwargs):
"""
Create the titles field using the titles up the parent chain
and set the initial value for ordering.
"""
if self.id is None:
self.content_model = self._meta.object_name.lower()
self.titles = self.title
super(Package, self).save(*args, **kwargs)
@classmethod
def get_content_models(cls):
"""
Return all Package subclasses.
"""
is_content_model = lambda m: m is not Package and issubclass(m, Package)
return list(filter(is_content_model, models.get_models()))
def get_content_model(self):
"""
Provies a generic method of retrieving the instance of the custom
content type's model for this Package.
"""
return getattr(self, self.content_model, None)
由於在Dango 1.9中刪除了models.get_model(),因此是AttributeError。 您應該使用dango.apps.apps.get_model()。 一些討論在這里和這里
這是您現在的使用方式。
from django.apps import apps
MyModel = apps.get_model('app name where the model is','name of the model you want to get from that app')
# Do your logic here with MyModel
但是,如果您只想獲取模型,為什么不立即將其導入? 您如何在下游使用代碼? 請注意,由於更改(從1.9開始),函數的屬性可能已更改。 因此,您可能需要考慮最新的模塊和功能來實現您的結果(以前使用過的結果)。 這意味着您需要進行更多工作才能與更高版本的Django保持同步,但是由於get_model的更改,您仍然可能會遇到問題。 總而言之,請查看代碼在做什么,並適應新版本的Django。
我不確定我是幫助過您還是困惑您。 抱歉,如果我稍后再做。
最好的祝願。
from django.apps import apps
ModelClass = apps.get_model('app_name.ModelClass')
您現在可以實例化該課程
mc = ModelClass()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.