本文整理汇总了Python中django.db.models.CASCADE属性的典型用法代码示例。如果您正苦于以下问题:Python models.CASCADE属性的具体用法?Python models.CASCADE怎么用?Python models.CASCADE使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类django.db.models
的用法示例。
在下文中一共展示了models.CASCADE属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ask_remove_enum_values
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
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(
db_type=db_type,
values=values),
[q for (k, q) in choices]) - 1]
if choice == models.SET:
return models.SET(self._ask_default())
return choice
示例2: __init__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def __init__(self, from_fields, to_fields, swappable=True, **kwargs):
self.from_fields = from_fields
self.to_fields = to_fields = to_fields
self.swappable = swappable
if 'rel' not in kwargs:
kwargs['rel'] = LayoutForeignObjectRel(
self, related_name=kwargs.pop('related_name', None),
related_query_name=kwargs.pop('related_query_name', None),
limit_choices_to=kwargs.pop('limit_choices_to', None),
parent_link=kwargs.pop('parent_link', False),
on_delete=kwargs.pop('on_delete', CASCADE),
)
kwargs['verbose_name'] = kwargs.get('verbose_name', None)
# We want to skip ForeignObject in the MRO, so we can't use super here
LayoutRelatedField.__init__(self, **kwargs)
示例3: test_parental_key_checks_clusterable_model
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def test_parental_key_checks_clusterable_model(self):
from django.core import checks
from django.db import models
from modelcluster.fields import ParentalKey
class Instrument(models.Model):
# Oops, BandMember is not a Clusterable model
member = ParentalKey(BandMember, on_delete=models.CASCADE)
class Meta:
# Prevent Django from thinking this is in the database
# This shouldn't affect the test
abstract = True
# Check for error
errors = Instrument.check()
self.assertEqual(1, len(errors))
# Check the error itself
error = errors[0]
self.assertIsInstance(error, checks.Error)
self.assertEqual(error.id, 'modelcluster.E001')
self.assertEqual(error.obj, Instrument.member.field)
self.assertEqual(error.msg, 'ParentalKey must point to a subclass of ClusterableModel.')
self.assertEqual(error.hint, 'Change tests.BandMember into a ClusterableModel or use a ForeignKey instead.')
示例4: test_parental_key_checks_related_name_is_not_plus
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def test_parental_key_checks_related_name_is_not_plus(self):
from django.core import checks
from django.db import models
from modelcluster.fields import ParentalKey
class Instrument(models.Model):
# Oops, related_name='+' is not allowed
band = ParentalKey(Band, related_name='+', on_delete=models.CASCADE)
class Meta:
# Prevent Django from thinking this is in the database
# This shouldn't affect the test
abstract = True
# Check for error
errors = Instrument.check()
self.assertEqual(1, len(errors))
# Check the error itself
error = errors[0]
self.assertIsInstance(error, checks.Error)
self.assertEqual(error.id, 'modelcluster.E002')
self.assertEqual(error.obj, Instrument.band.field)
self.assertEqual(error.msg, "related_name='+' is not allowed on ParentalKey fields")
self.assertEqual(error.hint, "Either change it to a valid name or remove it")
示例5: test_parental_key_checks_target_is_resolved_as_class
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def test_parental_key_checks_target_is_resolved_as_class(self):
from django.core import checks
from django.db import models
from modelcluster.fields import ParentalKey
class Instrument(models.Model):
banana = ParentalKey('Banana', on_delete=models.CASCADE)
class Meta:
# Prevent Django from thinking this is in the database
# This shouldn't affect the test
abstract = True
# Check for error
errors = Instrument.check()
self.assertEqual(1, len(errors))
# Check the error itself
error = errors[0]
self.assertIsInstance(error, checks.Error)
self.assertEqual(error.id, 'fields.E300')
self.assertEqual(error.obj, Instrument.banana.field)
self.assertEqual(error.msg, "Field defines a relation with model 'Banana', which is either not installed, or is abstract.")
示例6: setUpClass
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def setUpClass(cls):
"""Creates the test model in the database."""
super(LocalizedExpressionsTestCase, cls).setUpClass()
cls.TestModel1 = get_fake_model(
{"name": models.CharField(null=False, blank=False, max_length=255)}
)
cls.TestModel2 = get_fake_model(
{
"text": LocalizedField(),
"other": models.ForeignKey(
cls.TestModel1,
related_name="features",
on_delete=models.CASCADE,
),
}
)
示例7: __init__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def __init__(self, to, object_id_field='object_id', content_type_field='content_type',
for_concrete_model=True, related_query_name=None, limit_choices_to=None, **kwargs):
kwargs['rel'] = self.rel_class(
self, to,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
)
kwargs['blank'] = True
kwargs['on_delete'] = models.CASCADE
kwargs['editable'] = False
kwargs['serialize'] = False
# This construct is somewhat of an abuse of ForeignObject. This field
# represents a relation from pk to object_id field. But, this relation
# isn't direct, the join is generated reverse along foreign key. So,
# the from_field is object_id field, to_field is pk because of the
# reverse join.
super(GenericRelation, self).__init__(
to, from_fields=[object_id_field], to_fields=[], **kwargs)
self.object_id_field_name = object_id_field
self.content_type_field_name = content_type_field
self.for_concrete_model = for_concrete_model
示例8: delete
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def delete(self, *args, **kwargs):
# Clear delta history. Deltas can reference WfModules: if we don't
# clear the deltas, Django may decide to CASCADE to WfModule first and
# we'll raise a ProtectedError.
self.clear_deltas()
# Clear all minio data. We _should_ clear it in pre-delete hooks on
# StoredObject, UploadedFile, etc.; but [2019-06-03, adamhooper] the
# database is inconsistent and Django is hard to use so new bugs may
# crop up anyway.
#
# [2019-06-03, adamhooper] hooks never work in ORMs. Better would be
# to make `delete()` a controller method, not a funky mishmash of
# Django-ORM absurdities. TODO nix Django ORM.
#
# TL;DR we're double-deleting minio data, to be extra-safe. The user
# said "delete." We'll delete.
if self.id: # be extra-safe: use if-statement so we don't remove '/'
minio.remove_recursive(minio.StoredObjectsBucket, f"{self.id}/")
minio.remove_recursive(minio.UserFilesBucket, f"wf-{self.id}/")
super().delete(*args, **kwargs)
示例9: test_name
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def test_name(self):
"""
Tests the outputting of the correct name if assigned one.
"""
# First try using a "normal" field
field = models.CharField(max_length=65)
name, path, args, kwargs = field.deconstruct()
self.assertIsNone(name)
field.set_attributes_from_name("is_awesome_test")
name, path, args, kwargs = field.deconstruct()
self.assertEqual(name, "is_awesome_test")
self.assertIsInstance(name, six.text_type)
# Now try with a ForeignKey
field = models.ForeignKey("some_fake.ModelName", models.CASCADE)
name, path, args, kwargs = field.deconstruct()
self.assertIsNone(name)
field.set_attributes_from_name("author")
name, path, args, kwargs = field.deconstruct()
self.assertEqual(name, "author")
示例10: test_remove_field_m2m_with_through
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def test_remove_field_m2m_with_through(self):
project_state = self.set_up_test_model("test_rmflmmwt", second_model=True)
self.assertTableNotExists("test_rmflmmwt_ponystables")
project_state = self.apply_operations("test_rmflmmwt", project_state, operations=[
migrations.CreateModel("PonyStables", fields=[
("pony", models.ForeignKey('test_rmflmmwt.Pony', models.CASCADE)),
("stable", models.ForeignKey('test_rmflmmwt.Stable', models.CASCADE)),
]),
migrations.AddField(
"Pony", "stables",
models.ManyToManyField("Stable", related_name="ponies", through='test_rmflmmwt.PonyStables')
)
])
self.assertTableExists("test_rmflmmwt_ponystables")
operations = [migrations.RemoveField("Pony", "stables"), migrations.DeleteModel("PonyStables")]
self.apply_operations("test_rmflmmwt", project_state, operations=operations)
示例11: test_create_model_and_unique_together
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def test_create_model_and_unique_together(self):
author = ModelState("otherapp", "Author", [
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=200)),
])
book_with_author = ModelState("otherapp", "Book", [
("id", models.AutoField(primary_key=True)),
("author", models.ForeignKey("otherapp.Author", models.CASCADE)),
("title", models.CharField(max_length=200)),
], {
"index_together": {("title", "author")},
"unique_together": {("title", "author")},
})
changes = self.get_changes([self.book_with_no_author], [author, book_with_author])
# Right number of migrations?
self.assertEqual(len(changes['otherapp']), 1)
# Right number of actions?
migration = changes['otherapp'][0]
self.assertEqual(len(migration.operations), 4)
# Right actions order?
self.assertOperationTypes(
changes, 'otherapp', 0,
['CreateModel', 'AddField', 'AlterUniqueTogether', 'AlterIndexTogether']
)
示例12: test_duplicate_order_field
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def test_duplicate_order_field(self):
class Bar(models.Model):
class Meta:
app_label = 'order_with_respect_to'
class Foo(models.Model):
bar = models.ForeignKey(Bar, models.CASCADE)
order = models.OrderWrt()
class Meta:
order_with_respect_to = 'bar'
app_label = 'order_with_respect_to'
count = 0
for field in Foo._meta.local_fields:
if isinstance(field, models.OrderWrt):
count += 1
self.assertEqual(count, 1)
示例13: test_sealed_prefetch_related_non_sealable_model
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def test_sealed_prefetch_related_non_sealable_model(self):
class NonSealableClimate(models.Model):
objects = SealableQuerySet.as_manager()
class Meta:
db_table = Climate._meta.db_table
class NonSealableLocationClimatesThrough(models.Model):
climate = models.ForeignKey(NonSealableClimate, models.CASCADE)
location = models.ForeignKey('NonSealableLocation', models.CASCADE)
class Meta:
db_table = Location.climates.through._meta.db_table
class NonSealableLocation(models.Model):
climates = models.ManyToManyField(NonSealableClimate, through=NonSealableLocationClimatesThrough)
class Meta:
db_table = Location._meta.db_table
queryset = SealableQuerySet(model=NonSealableLocation)
instance = queryset.prefetch_related('climates').seal().get()
self.assertTrue(instance._state.sealed)
with self.assertNumQueries(0):
self.assertTrue(instance.climates.all()[0]._state.sealed)
示例14: test_foreign_key_to_missing_model
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def test_foreign_key_to_missing_model(self):
# Model names are resolved when a model is being created, so we cannot
# test relative fields in isolation and we need to attach them to a
# model.
class Model(models.Model):
foreign_key = models.ForeignKey('Rel1', models.CASCADE)
field = Model._meta.get_field('foreign_key')
self.assertEqual(field.check(), [
Error(
"Field defines a relation with model 'Rel1', "
"which is either not installed, or is abstract.",
obj=field,
id='fields.E300',
),
])
示例15: test_relationship_model_missing_foreign_key
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CASCADE [as 别名]
def test_relationship_model_missing_foreign_key(self):
class Person(models.Model):
pass
class Group(models.Model):
members = models.ManyToManyField('Person', through="InvalidRelationship")
class InvalidRelationship(models.Model):
group = models.ForeignKey(Group, models.CASCADE)
# No foreign key to Person
field = Group._meta.get_field('members')
self.assertEqual(field.check(from_model=Group), [
Error(
"The model is used as an intermediate model by "
"'invalid_models_tests.Group.members', but it does not have "
"a foreign key to 'Group' or 'Person'.",
obj=InvalidRelationship,
id='fields.E336',
),
])