本文整理汇总了Python中django.apps.apps.get_model方法的典型用法代码示例。如果您正苦于以下问题:Python apps.get_model方法的具体用法?Python apps.get_model怎么用?Python apps.get_model使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.apps.apps
的用法示例。
在下文中一共展示了apps.get_model方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: actions_have_consistent_hashes
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def actions_have_consistent_hashes(app_configs, **kwargs):
errors = []
try:
Action = apps.get_model("recipes", "Action")
actions = list(Action.objects.filter(implementation__isnull=False))
except (ProgrammingError, OperationalError, ImproperlyConfigured) as e:
errors.append(Info(f"Could not retrieve actions: {e}", id=INFO_COULD_NOT_RETRIEVE_ACTIONS))
else:
for action in actions:
if action.compute_implementation_hash() != action.implementation_hash:
msg = "Action '{action}' (id={action.id}) has a mismatched hash".format(
action=action
)
errors.append(Error(msg, id=ERROR_MISMATCHED_ACTION_HASH))
return errors
示例2: test_phone_registration_sends_message
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def test_phone_registration_sends_message(client, mocker, backend):
url = reverse("phone-register")
phone_number = PHONE_NUMBER
data = {"phone_number": phone_number}
twilio_api = mocker.patch(
"phone_verify.services.PhoneVerificationService.send_verification"
)
response = client.post(url, data)
assert response.status_code == 200
assert twilio_api.called
assert "session_token" in response.data
SMSVerification = apps.get_model("phone_verify", "SMSVerification")
assert SMSVerification.objects.get(
session_token=response.data["session_token"], phone_number=phone_number
)
示例3: get_usersettings_model
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def get_usersettings_model():
"""
Returns the ``UserSettings`` model that is active in this project.
"""
try:
from django.apps import apps
get_model = apps.get_model
except ImportError:
from django.db.models.loading import get_model
try:
app_label, model_name = settings.USERSETTINGS_MODEL.split('.')
except ValueError:
raise ImproperlyConfigured('USERSETTINGS_MODEL must be of the '
'form "app_label.model_name"')
usersettings_model = get_model(app_label, model_name)
if usersettings_model is None:
raise ImproperlyConfigured('USERSETTINGS_MODEL refers to model "%s" that has '
'not been installed' % settings.USERSETTINGS_MODEL)
return usersettings_model
示例4: handle
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def handle(self, *args, **options):
app_name = options['app']
model_name = options['model']
field_name = options['field']
model = apps.get_model(app_name, model_name)
fields = model._meta.get_fields()
matching_fields = [f for f in fields if isinstance(f, models.FileField) and f.name == field_name]
field = matching_fields[0]
storage = field.storage
for o in model.objects.all():
# threads aren't usually interrupted: https://stackoverflow.com/a/842567/6871666
t = Thread(target=move_file, args=(model, storage, field_name, field, o))
t.start()
t.join()
示例5: context
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def context(self, context):
btns = []
for b in self.q_btns:
btn = {}
if 'model' in b:
model = self.get_model(b['model'])
if not self.user.has_perm("%s.view_%s" % (model._meta.app_label, model._meta.model_name)):
continue
btn['url'] = reverse("%s:%s_%s_%s" % (self.admin_site.app_name, model._meta.app_label,
model._meta.model_name, b.get('view', 'changelist')))
btn['title'] = model._meta.verbose_name
btn['icon'] = self.dashboard.get_model_icon(model)
else:
try:
btn['url'] = reverse(b['url'])
except NoReverseMatch:
btn['url'] = b['url']
if 'title' in b:
btn['title'] = b['title']
if 'icon' in b:
btn['icon'] = b['icon']
btns.append(btn)
context.update({'btns': btns})
示例6: export
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def export(dirname):
"""
Take all the annotated images, copy them to the specified directory,
and write out annotated.json with the annotation for each image.
"""
Image = apps.get_model('train', 'Image')
annotated = Image.objects.filter(annotation__isnull=False)
data = []
for i in annotated:
base = os.path.basename(i.path)
# copy image to directory
shutil.copy(i.path, os.path.join(dirname, base))
# add bounding boxes to JSON
data.append({
'image_name': base,
'image_annotation': i.annotation
})
with open(os.path.join(dirname, 'annotated.json'), 'w') as f:
json.dump(data, f)
return annotated.count()
示例7: _load_field
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def _load_field(app_label, model_name, field_name):
return apps.get_model(app_label, model_name)._meta.get_field(field_name)
# A guide to Field parameters:
#
# * name: The name of the field specified in the model.
# * attname: The attribute to use on the model object. This is the same as
# "name", except in the case of ForeignKeys, where "_id" is
# appended.
# * db_column: The db_column specified in the model (or None).
# * column: The database column for this field. This is the same as
# "attname", except if db_column is specified.
#
# Code that introspects values, or does other dynamic things, should use
# attname. For example, this gets the primary key value of object "obj":
#
# getattr(obj, opts.pk.attname)
示例8: handle
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def handle(self, **options):
warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)
call_command("migrate", **options)
try:
apps.get_model('auth', 'Permission')
except LookupError:
return
UserModel = get_user_model()
if not UserModel._default_manager.exists() and options.get('interactive'):
msg = ("\nYou have installed Django's auth system, and "
"don't have any superusers defined.\nWould you like to create one "
"now? (yes/no): ")
confirm = input(msg)
while 1:
if confirm not in ('yes', 'no'):
confirm = input('Please enter either "yes" or "no": ')
continue
if confirm == 'yes':
call_command("createsuperuser", interactive=True, database=options['database'])
break
示例9: _get_model_from_node
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def _get_model_from_node(self, node, attr):
"""
Helper to look up a model from a <object model=...> or a <field
rel=... to=...> node.
"""
model_identifier = node.getAttribute(attr)
if not model_identifier:
raise base.DeserializationError(
"<%s> node is missing the required '%s' attribute"
% (node.nodeName, attr))
try:
return apps.get_model(model_identifier)
except (LookupError, TypeError):
raise base.DeserializationError(
"<%s> node has invalid model identifier: '%s'"
% (node.nodeName, model_identifier))
示例10: __init__
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def __init__(self, **kwargs):
self.hashid_salt = kwargs.pop('salt', settings.HASHID_FIELD_SALT)
self.hashid_min_length = kwargs.pop('min_length', 7)
self.hashid_alphabet = kwargs.pop('alphabet', Hashids.ALPHABET)
source_field = kwargs.pop('source_field', None)
if source_field:
from hashid_field import HashidField, HashidAutoField
if isinstance(source_field, str):
try:
app_label, model_name, field_name = source_field.split(".")
except ValueError:
raise ValueError(self.usage_text)
model = apps.get_model(app_label, model_name)
source_field = model._meta.get_field(field_name)
elif not isinstance(source_field, (HashidField, HashidAutoField)):
raise TypeError(self.usage_text)
self.hashid_salt, self.hashid_min_length, self.hashid_alphabet = \
source_field.salt, source_field.min_length, source_field.alphabet
self._hashids = Hashids(salt=self.hashid_salt, min_length=self.hashid_min_length, alphabet=self.hashid_alphabet)
super().__init__(**kwargs)
示例11: __init__
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def __init__(self, model_class, allow_unsaved=False, *args, **kwargs):
super(ModelField, self).__init__(*args, **kwargs)
try:
model_class._meta.model_name
except AttributeError:
assert isinstance(model_class, str), self.error_model_class % {
'cls_name': self.__class__.__name__,
'model_class': model_class
}
self.model_class = model_class
if isinstance(model_class, str):
label = model_class.split('.')
app_label = ".".join(label[:-1])
model_name = label[-1]
self.model_class = apps.get_model(app_label, model_name)
self.allow_unsaved = allow_unsaved
示例12: convert_all_videos
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def convert_all_videos(app_label, model_name, object_pk):
"""
Automatically converts all videos of a given instance.
"""
# get instance
Model = apps.get_model(app_label=app_label, model_name=model_name)
instance = Model.objects.get(pk=object_pk)
# search for `VideoFields`
fields = instance._meta.fields
for field in fields:
if isinstance(field, VideoField):
if not getattr(instance, field.name):
# ignore empty fields
continue
# trigger conversion
fieldfile = getattr(instance, field.name)
convert_video(fieldfile)
示例13: populate_labelling_msg_fields
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def populate_labelling_msg_fields(apps, schema_editor):
Labelling = apps.get_model("msgs", "Labelling")
Message = apps.get_model("msgs", "Message")
max_id = 0
num_updated = 0
while True:
id_batch = list(
Labelling.objects.filter(id__gt=max_id, message_created_on=None)
.values_list("id", flat=True)
.order_by("id")[:BATCH_SIZE]
)
if not id_batch:
break
Labelling.objects.filter(id__in=id_batch).update(
message_is_flagged=Subquery(Message.objects.filter(id=OuterRef("message_id")).values("is_flagged")[:1]),
message_is_archived=Subquery(Message.objects.filter(id=OuterRef("message_id")).values("is_archived")[:1]),
message_created_on=Subquery(Message.objects.filter(id=OuterRef("message_id")).values("created_on")[:1]),
)
max_id = id_batch[-1]
num_updated += len(id_batch)
print(f" > Updated {num_updated} instances of labelling")
示例14: _check_swappable
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def _check_swappable(cls):
"""Check if the swapped model exists."""
errors = []
if cls._meta.swapped:
try:
apps.get_model(cls._meta.swapped)
except ValueError:
errors.append(
checks.Error(
"'%s' is not of the form 'app_label.app_name'." % cls._meta.swappable,
id='models.E001',
)
)
except LookupError:
app_label, model_name = cls._meta.swapped.split('.')
errors.append(
checks.Error(
"'%s' references '%s.%s', which has not been "
"installed, or is abstract." % (
cls._meta.swappable, app_label, model_name
),
id='models.E002',
)
)
return errors
示例15: _get_sitemap_full_url
# 需要导入模块: from django.apps import apps [as 别名]
# 或者: from django.apps.apps import get_model [as 别名]
def _get_sitemap_full_url(sitemap_url):
if not django_apps.is_installed('django.contrib.sites'):
raise ImproperlyConfigured("ping_google requires django.contrib.sites, which isn't installed.")
if sitemap_url is None:
try:
# First, try to get the "index" sitemap URL.
sitemap_url = reverse('django.contrib.sitemaps.views.index')
except NoReverseMatch:
try:
# Next, try for the "global" sitemap URL.
sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
except NoReverseMatch:
pass
if sitemap_url is None:
raise SitemapNotFound("You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.")
Site = django_apps.get_model('sites.Site')
current_site = Site.objects.get_current()
return 'http://%s%s' % (current_site.domain, sitemap_url)