本文整理汇总了Python中django.db.models.Model类的典型用法代码示例。如果您正苦于以下问题:Python Model类的具体用法?Python Model怎么用?Python Model使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Model类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: recache_lat_long
def recache_lat_long(apps, schema_editor):
from issues.models import Issue as CurrentIssue
Issue = apps.get_model('issues', 'Issue')
for issue in Issue.objects.filter(location__isnull=False):
issue._cache_location = CurrentIssue._cache_location
issue._cache_location()
Model.save(self=issue, update_fields=('lat', 'long'))
示例2: post
def post(self, request, *args, **kwargs):
if not request.user.has_perm('agenda.can_manage_agenda'):
messages.error(
request,
_('You are not authorized to manage the agenda.'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
transaction.commit()
for item in Item.objects.all():
form = ItemOrderForm(request.POST, prefix="i%d" % item.id)
if form.is_valid():
try:
parent = Item.objects.get(id=form.cleaned_data['parent'])
except Item.DoesNotExist:
parent = None
item.weight = form.cleaned_data['weight']
item.parent = parent
Model.save(item)
else:
transaction.rollback()
messages.error(
request, _('Errors when reordering of the agenda'))
break
else:
Item.objects.rebuild()
# TODO: assure, that it is a valid tree
context = self.get_context_data(**kwargs)
transaction.commit()
if get_active_slide()['callback'] == 'agenda':
update_projector()
context = self.get_context_data(**kwargs)
transaction.commit()
return self.render_to_response(context)
示例3: handle
def handle(self, *args, **options):
dry_run = options['dry_run']
#verbosity = options['verbosity']
stale_cts = {}
for ct in ContentType.objects.all():
if ct.model_class() is None:
stale_cts[ct.pk] = ct
items = (ContentItem.objects
.non_polymorphic() # very important, or polymorphic skips them on fetching derived data
.filter(polymorphic_ctype__in=list(stale_cts.keys()))
.order_by('polymorphic_ctype', 'pk')
)
if not items:
self.stdout.write("No stale items found.")
return
if dry_run:
self.stdout.write("The following content items are stale:")
else:
self.stdout.write("The following content items were stale:")
for item in items:
ct = stale_cts[item.polymorphic_ctype_id]
self.stdout.write("- #{id} points to removed {app_label}.{model}".format(id=item.pk, app_label=ct.app_label, model=ct.model))
if not dry_run:
try:
item.delete()
except PluginNotFound:
Model.delete(item)
示例4: save
def save(self, *args, **kwargs):
if not self.pk and self.is_active(self.instance):
raise RequestLimitExceeded(
"The number of open requests for "
"instance %s has been exceeded."
% self.instance.provider_alias)
Model.save(self, *args, **kwargs)
示例5: remove_stale_items
def remove_stale_items(self, stale_cts):
"""
See if there are items that point to a removed model.
"""
stale_ct_ids = list(stale_cts.keys())
items = (ContentItem.objects
.non_polymorphic() # very important, or polymorphic skips them on fetching derived data
.filter(polymorphic_ctype__in=stale_ct_ids)
.order_by('polymorphic_ctype', 'pk')
)
if not items:
self.stdout.write("No stale items found.")
return
if self.dry_run:
self.stdout.write("The following content items are stale:")
else:
self.stdout.write("The following content items were stale:")
for item in items:
ct = stale_cts[item.polymorphic_ctype_id]
self.stdout.write("- #{id} points to removed {app_label}.{model}".format(
id=item.pk, app_label=ct.app_label, model=ct.model
))
if not self.dry_run:
try:
item.delete()
except PluginNotFound:
Model.delete(item)
示例6: __new__
def __new__(cls, name, bases, attrs):
module = attrs.pop("__module__")
parents = [b for b in bases if isinstance(b, ModelMetaClass)]
if parents:
for obj_name, obj in attrs.items():
Model.add_to_class(obj_name, obj)
return super(ModelMetaClass, cls).__new__(cls, name, bases, attrs)
示例7: enlarged_create
def enlarged_create(Model, filter_kwargs, commit=True):
filter_kwargs, m2m_kwargs = separate_m2m_kwargs(Model, filter_kwargs)
obj = Model(**filter_kwargs)
if commit:
obj.save()
for k, v in m2m_kwargs.items():
getattr(obj, k).add(*v)
return obj
示例8: save
def save(self, *args, **kwargs):
self.ascii_tag = unidecode(self.tag)
words = self.ascii_tag.split()
known_words_list = known_words(words)
for word in words:
new_word = Word(word)
if not new_word in known_words_list:
new_word.save()
Model.save(self, *args, **kwargs)
示例9: versao_1_2_2
def versao_1_2_2(cmd, *args):
"""
Atualizações pra versão 1.2.2.
Deve ser chamada após exportar o banco de dados pra um arquivo de
dump JSON e remover o arquivo do banco de dados.
Ações:
- Cria um novo banco de dados e o superusuário padrão
- Faz as conversões necessárias sobre o dump nos modelos que mudaram
- Importa o dump convertido pro banco de dados
- Carrega fixture de feriados bancários
Argumentos da linha de comando:
- dump_file: arquivo de dump do banco de dados na versão
1.2.1
"""
if len(args) != 1:
raise CommandError("Uso: atualizar 1.2.2 <dump_file>\n\ndump: arquivo de dump do banco de dados anterior (JSON)")
sync_and_evolve()
criar_superusuario()
print("Convertendo entradas no modelo antigo pro novo modelo...")
novo_bd_json = converter(args[0])
tmp_dump_filename = "fixture_convertida.json"
print("Armazenando dados convertidos em {tmp_dump_filename}".format(**vars()))
with open(tmp_dump_filename, "w") as tmp_dump_file:
tmp_dump_file.write(novo_bd_json)
print("Carregando dados convertidos no banco de dados...")
call_command("loaddata", tmp_dump_filename)
print("Removendo arquivo temporário...")
os.remove(tmp_dump_filename)
print("Carregando fixture de feriados bancários...")
call_command("loaddata", "feriados_bancarios")
print("Reunindo arquivos estáticos...")
call_command("collectstatic", interactive=False)
print("Re-salvando os pagamentos com cartões pra preencher data de depósito")
for pagamento in PagamentoComCartao.objects.all():
pagamento.data_do_deposito = pagamento._data_do_deposito()
Model.save(pagamento)
示例10: __init__
def __init__(self, instance: Model = None, deleted: bool = False, collection_string: str = None,
id: int = None, full_data: Dict[str, Any] = None, information: Dict[str, Any] = None) -> None:
"""
Do not use this. Use the methods from_instance() or from_values().
"""
self.instance = instance
self.deleted = deleted
self.full_data = full_data
self.information = information or {}
if instance is not None:
# Collection element is created via instance
self.collection_string = instance.get_collection_string()
self.id = instance.pk
elif collection_string is not None and id is not None:
# Collection element is created via values
self.collection_string = collection_string
self.id = id
else:
raise RuntimeError(
'Invalid state. Use CollectionElement.from_instance() or '
'CollectionElement.from_values() but not CollectionElement() '
'directly.')
if self.is_deleted():
# Delete the element from the cache, if self.is_deleted() is True:
full_data_cache.del_element(self.collection_string, self.id)
else:
# The call to get_full_data() has some sideeffects. When the object
# was created with from_instance() or the object is not in the cache
# then get_full_data() will save the object into the cache.
# This will also raise a DoesNotExist error, if the object does
# neither exist in the cache nor in the database.
self.get_full_data()
示例11: rename_all_files
def rename_all_files():
"""
Rename the data files according to the scheme:
yyyy/mm/dd/id.h5
"""
for curve in CurveDB.objects.all():
full_name_old = curve.get_full_filename()
new_name = osp.join(
curve.params["date"].strftime('%Y/%m/%d'),
str(curve.id) + '.h5')
curve.data_file = new_name
if not osp.exists(full_name_old):
print 'file ' + full_name_old + " doesn't exist"
else:
shutil.move(full_name_old, curve.get_full_filename())
Model.save(curve)
示例12: modelcopy
def modelcopy(obj: models.Model):
n = obj.__class__()
for f in obj._meta.fields:
val = getattr(obj, f.name)
if isinstance(val, models.Model):
setattr(n, f.name, copy.copy(val))
else:
setattr(n, f.name, copy.deepcopy(val))
return n
示例13: save
def save(self, *args, **kwargs):
"""Overwrites Model.save().
We have to be very careful to never overwrite a request, so
often the request must be read from the database prior to saving.
The safe parameter being set to True enables this behavior.
"""
if kwargs.pop('safe', False):
self.request = type(self).objects.get(id=self.id).request
return Model.save(self, *args, **kwargs)
示例14: remove_stale_pages
def remove_stale_pages(self, stale_cts):
"""
See if there are items that point to a removed model.
"""
stale_ct_ids = list(stale_cts.keys())
pages = (UrlNode.objects
.non_polymorphic() # very important, or polymorphic skips them on fetching derived data
.filter(polymorphic_ctype__in=stale_ct_ids)
.order_by('polymorphic_ctype', 'pk')
)
if not pages:
self.stdout.write("No stale pages found.")
return
if self.dry_run:
self.stdout.write("The following pages are stale:")
else:
self.stdout.write("The following pages were stale:")
removed_pages = 0
for page in pages:
ct = stale_cts[page.polymorphic_ctype_id]
self.stdout.write("- #{id} points to removed {app_label}.{model}".format(
id=page.pk, app_label=ct.app_label, model=ct.model
))
if not self.dry_run:
try:
page.delete()
removed_pages += 1
except PageTypeNotFound:
Model.delete(page)
if removed_pages:
self.stdout.write("Note, when the removed pages contain content items, "
"also call `manage.py remove_stale_contentitems --remove-unreferenced")
示例15: delete
def delete(self, no_mptt=False, *args, **kwargs):
if no_mptt:
Model.delete(self, *args, **kwargs)
else:
super(CMSPlugin, self).delete(*args, **kwargs)