Python django.db.models.PROTECT Examples

The following are 6 code examples for showing how to use django.db.models.PROTECT(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: django-more   Author: ashleywaite   File:    License: BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def ask_remove_enum_values(self, db_type, values):
        """ How to treat records with deleted enum values. """
        # Ordered ensures
        choices = [
            (models.CASCADE, "Cascade - Delete records with removed values"),
            (models.PROTECT, "Protect - Block migrations if records contain removed values"),
            (models.SET_NULL, "Set NULL - Set value to NULL"),
            (models.SET_DEFAULT, "Set default - Set value to field default"),
            (models.SET, "Set value - Provide a one off default now"),
            (models.DO_NOTHING, "Do nothing - Consistency must be handled elsewhere"),
            (None, "Leave it to field definitions")]
        choice, _ = choices[self._choice_input(
            "Enum {db_type} has had {values} removed, "
            "existing records may need to be updated. "
            "Override update behaviour or do nothing and follow field behaviour.".format(
            [q for (k, q) in choices]) - 1]
        if choice == models.SET:
            return models.SET(self._ask_default())
        return choice 
Example 2
Project: django-more   Author: ashleywaite   File:    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, db_type, add_values=None, remove_values=None, on_delete=models.PROTECT):
        self.db_type = db_type
        self.add_values = set(add_values or ())
        self.remove_values = set(remove_values or ())
        self.on_delete = on_delete 
Example 3
Project: Politikon   Author: KlubJagiellonski   File:    License: GNU General Public License v2.0 5 votes vote down vote up
def create_snapshot_model(cls, fields=[]):
    """ Dynamically create a main Model, 1-1 with the model being snapshotted. """
    # Models must have unique names, so we create a name by suffixing model class name with 'Snapshot'
    name = cls.__name__ + 'Snapshot'

    class Meta:
        db_table = '%s_snapshot' % cls._meta.db_table
        app_label = cls._meta.app_label
        verbose_name = u'%s - snapshot' % cls._meta.verbose_name
        verbose_name_plural = u'%s - snapshoty' % cls._meta.verbose_name
        ordering = ['-created_at']

    # Set up a dictionary to simulate declarations within a class.
    attrs = {
        '__module__': cls.__module__,
        'Meta': Meta,
        'id': models.AutoField(primary_key=True),
        'created_at': models.DateTimeField(u"stworzony dnia", auto_now_add=True),
        'snapshot_of': models.ForeignKey(cls, verbose_name=u"dotyczy", null=False, on_delete=models.PROTECT, related_name="snapshots"),
        '__unicode__': lambda self: u'snapshot',

    # Copy fields
    for field_name in fields:
        target_field = cls._meta.get_field_by_name(field_name)[0]
        attrs[field_name] = copy_field(target_field)

    return type(name, (models.Model,), attrs) 
Example 4
Project: wagtail   Author: wagtail   File:    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
            msg = _("%(model_name)s '%(instance)s' deleted.") % {
                'model_name': self.verbose_name, 'instance': self.instance
            messages.success(request, msg)
            return redirect(self.index_url)
        except models.ProtectedError:
            linked_objects = []
            fields = self.model._meta.fields_map.values()
            fields = (obj for obj in fields if not isinstance(
                obj.field, ManyToManyField))
            for rel in fields:
                if rel.on_delete == models.PROTECT:
                    if isinstance(rel, OneToOneRel):
                            obj = getattr(self.instance, rel.get_accessor_name())
                        except ObjectDoesNotExist:
                        qs = getattr(self.instance, rel.get_accessor_name())
                        for obj in qs.all():
            context = self.get_context_data(
            return self.render_to_response(context) 
Example 5
Project: wagtailmodeladmin   Author: rkhleics   File:    License: MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        if request.POST:
                    _("{model} '{instance}' deleted.").format(
                        model=self.model_name, instance=self.instance))
                return redirect(self.get_index_url)
            except models.ProtectedError:
                    request, _(
                        "{model} '{instance}' could not be deleted."
                    ).format(model=self.model_name, instance=self.instance))

                linked_objects = []
                for rel in self.model._meta.get_all_related_objects():
                    if rel.on_delete == models.PROTECT:
                        qs = getattr(self.instance, rel.get_accessor_name())
                        for obj in qs.all():

                context = {
                    'view': self,
                    'instance': self.instance,
                    'error_protected': True,
                    'linked_objects': linked_objects,
        return self.render_to_response(context) 
Example 6
Project: jorvik   Author: CroceRossaItaliana   File:    License: GNU General Public License v3.0 5 votes vote down vote up
def media_consumi(self):
        rifornimenti = Rifornimento.objects.filter(veicolo=self)
        litri = 0
        for rifornimento in rifornimenti:
            litri += rifornimento.consumo_carburante
            ultimo_rifornimento = Rifornimento.objects.filter(veicolo=self).latest("data")
            primo_rifornimento = Rifornimento.objects.filter(veicolo=self).earliest("data")
        except Rifornimento.DoesNotExist:
            return 0
        km = ultimo_rifornimento.contachilometri - primo_rifornimento.contachilometri
        litri -= ultimo_rifornimento.consumo_carburante
        if litri != 0:
            return round(km/litri, 2)
            return 0

# class Immatricolazione(ModelloSemplice, ConMarcaTemporale):
#     """
#     Rappresenta una pratica di immatricolazione di un Veicolo
#     Una pratica viene istruita da un ufficio motorizzazione per conto di una unita' CRI richiedente.
#     La stessa viene sottoposta a due stadi di approvazione, in seguito alla istruzione. Quando la
#     pratica termina, il veicolo viene immatricolato ed entra in servizio.
#     """
#     class Meta:
#         verbose_name = "Pratica di Immatricolazione"
#         verbose_name_plural = "Pratiche di Immatricolazione"
#     richiedente = models.ForeignKey(Sede, related_name='immatricolazioni_richieste', null=True, on_delete=models.SET_NULL)
#     ufficio = models.ForeignKey(Sede, related_name='immatricolazioni_istruite', on_delete=models.PROTECT)
#     veicolo = models.ForeignKey(Veicolo, related_name='richieste_immatricolazione', on_delete=models.CASCADE)