我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.CASCADE。
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
def set_up_test_model(self): operations = [ migrations.CreateModel( "Pony", [ ('pony_id', models.AutoField(primary_key=True)), ('pink', models.IntegerField(default=3)), ('weight', models.FloatField()) ], ), migrations.CreateModel( 'Rider', [ ('rider_id', models.AutoField(primary_key=True)), ('pony', models.ForeignKey('Pony', on_delete=models.CASCADE)) ], ), ] return self.apply_operations('tests', ProjectState(), operations)
def save_user_profile(sender, instance, **kwargs): instance.profile.save() # class ParsedProfile(models.Model): # user = models.OneToOneField(User, on_delete=models.CASCADE) # name = models.CharField(max_length=250) # header = models.CharField(max_length=500, null=True) # url = models.CharField(max_length=500) # school = models.CharField(max_length=500, null=True) # school_program = models.CharField(max_length=500, null=True) # # # class JobTitle(models.Model): # profile = models.ForeignKey(ParsedProfile, on_delete=models.CASCADE) # job = models.CharField(max_length=500, null=True) # # # class Location(models.Model): # profile = models.ForeignKey(ParsedProfile, on_delete=models.CASCADE) # loc = models.CharField(max_length=500, default=None) # Below is All The Profiles that were originally in DB and added new ones by User # Initial Profiles, only 2000 were in DB (mainly SE/CS focused)
def __init__(self, to, on_delete=None, to_field=None, **kwargs): kwargs['unique'] = True if on_delete is None: warnings.warn( "on_delete will be a required arg for %s in Django 2.0. Set " "it to models.CASCADE on models and in existing migrations " "if you want to maintain the current default behavior. " "See https://docs.djangoproject.com/en/%s/ref/models/fields/" "#django.db.models.ForeignKey.on_delete" % ( self.__class__.__name__, get_docs_version(), ), RemovedInDjango20Warning, 2) on_delete = CASCADE elif not callable(on_delete): warnings.warn( "The signature for {0} will change in Django 2.0. " "Pass to_field='{1}' as a kwarg instead of as an arg.".format( self.__class__.__name__, on_delete, ), RemovedInDjango20Warning, 2) to_field = on_delete on_delete = CASCADE # Avoid warning in superclass super(OneToOneField, self).__init__(to, on_delete, to_field=to_field, **kwargs)
def createBaseAttr(model): class GeneratedAttr(AbstractBaseAttr): """ An abstract Base Class used to generate actual Attr classes with an object """ object = models.ForeignKey(model, related_name='attrs', on_delete=models.CASCADE) _model = model class Meta: abstract = True unique_together = (('attribute', 'object'), ) return GeneratedAttr
def __str__(self): return self.disability_name # student = models.ForeignKey(StudentInfo, on_delete=models.CASCADE)
def test_invalid_base_fields(self): class Related(models.Model): field = encrypt( models.ForeignKey('fields.EncryptedIntegerModel', models.CASCADE)) class Meta: app_label = 'myapp' obj = Related() errors = obj.check() self.assertEqual(1, len(errors)) self.assertEqual('encrypted.E002', errors[0].id)
def __init__(self, model, on_delete=models.CASCADE, **kwargs): self._make_key = lambda name: models.ForeignKey(model, related_query_name=name.lower(), on_delete=on_delete, **kwargs)
def test_content_type(self): field = ServeLog._meta.get_field('content_type') self.assertModelPKField(field, ContentType, models.CASCADE, False, False)
def test_menu(self): field = MenuMenuItem._meta.get_field('menu') self.assertModelParentalKeyField(field, Menu, models.CASCADE, False, False, 'menu_items')
def test_page(self): field = BasicPageCarouselItem._meta.get_field('page') self.assertModelParentalKeyField(field, BasicPage, models.CASCADE, False, False)
def test_page(self): field = BasicPageSectionItem._meta.get_field('page') self.assertModelParentalKeyField(field, BasicPage, models.CASCADE, False, False)
def __str__(self): return self.name #class currentOwner(models.Model): #current ownership (user foreign key) # currOwn = models.ForeignKey(Customer, on_delete=models.CASCADE) #current ownership (user foreign key # def __str__(self): # return self.currOwn #ADD HISTORY PART
def __str__(self): return 'Email: ' + self.user.email # class UserSettings(models.Model): # user = models.OneToOneField(UserProfile,on_delete=models.CASCADE,primary_key=True)
def tearDown(self): with connection.cursor() as cursor: for schema in Schema.objects.all(): cursor.execute('DROP SCHEMA IF EXISTS {0} CASCADE'.format(schema.schema)) cursor.execute('SET search_path TO __template__,public') cursor.execute('DROP TABLE IF EXISTS tests_rider') cursor.execute("DROP TABLE IF EXISTS tests_pony")
def __init__(self, to, on_delete=None, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, to_field=None, db_constraint=True, **kwargs): try: to._meta.model_name except AttributeError: assert isinstance(to, six.string_types), ( "%s(%r) is invalid. First parameter to ForeignKey must be " "either a model, a model name, or the string %r" % ( self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT, ) ) else: # For backwards compatibility purposes, we need to *try* and set # the to_field during FK construction. It won't be guaranteed to # be correct until contribute_to_class is called. Refs #12190. to_field = to_field or (to._meta.pk and to._meta.pk.name) if on_delete is None: warnings.warn( "on_delete will be a required arg for %s in Django 2.0. Set " "it to models.CASCADE on models and in existing migrations " "if you want to maintain the current default behavior. " "See https://docs.djangoproject.com/en/%s/ref/models/fields/" "#django.db.models.ForeignKey.on_delete" % ( self.__class__.__name__, get_docs_version(), ), RemovedInDjango20Warning, 2) on_delete = CASCADE elif not callable(on_delete): warnings.warn( "The signature for {0} will change in Django 2.0. " "Pass to_field='{1}' as a kwarg instead of as an arg.".format( self.__class__.__name__, on_delete, ), RemovedInDjango20Warning, 2) on_delete, to_field = to_field, on_delete kwargs['rel'] = self.rel_class( self, to, to_field, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) kwargs['db_index'] = kwargs.get('db_index', True) super(ForeignKey, self).__init__( to, on_delete, from_fields=['self'], to_fields=[to_field], **kwargs) self.db_constraint = db_constraint
def create_many_to_many_intermediary_model(field, klass): from django.db import models def set_managed(model, related, through): through._meta.managed = model._meta.managed or related._meta.managed to_model = resolve_relation(klass, field.remote_field.model) name = '%s_%s' % (klass._meta.object_name, field.name) lazy_related_operation(set_managed, klass, to_model, name) to = make_model_tuple(to_model)[1] from_ = klass._meta.model_name if to == from_: to = 'to_%s' % to from_ = 'from_%s' % from_ meta = type(str('Meta'), (object,), { 'db_table': field._get_m2m_db_table(klass._meta), 'auto_created': klass, 'app_label': klass._meta.app_label, 'db_tablespace': klass._meta.db_tablespace, 'unique_together': (from_, to), 'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to}, 'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to}, 'apps': field.model._meta.apps, }) # Construct and return the new class. return type(str(name), (models.Model,), { 'Meta': meta, '__module__': klass.__module__, from_: models.ForeignKey( klass, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), to: models.ForeignKey( to_model, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ) })
def deactivate(self): """Deactivate a subscriber. Send an async post to the BTS to deactivate the subscriber. Sign the request using JWT. Note that we do not also send deactivate number commands -- the BTS will handle that on its own. If the sub does not have an associated BTS, the sub's previous tower may have been deleted. We can still delete the sub we just do not have to notify a tower. """ if self.bts: url = '%s/config/deactivate_subscriber' % self.bts.inbound_url data = { 'imsi': self.imsi, # Add a UUID as a nonce for the message. 'msgid': str(uuid.uuid4()), } serializer = itsdangerous.JSONWebSignatureSerializer( self.bts.secret) signed_data = { 'jwt': serializer.dumps(data), } # Retry the async_post for three months until it succeeds. retry_delay = 60 * 10 three_months = 3 * 30 * 24 * 60 * 60. max_retries = int(three_months / retry_delay) celery_app.send_task( 'endagaweb.tasks.async_post', (url, signed_data), max_retries=max_retries) # Deactivate all associated Numbers from this Sub. numbers = Number.objects.filter(subscriber=self) with transaction.atomic(): now = django.utils.timezone.now() # Create a 'delete_imsi' UsageEvent. bts_uuid = None if self.bts: bts_uuid = self.bts.uuid event = UsageEvent.objects.create( subscriber=self, date=now, bts=self.bts, kind='delete_imsi', subscriber_imsi=self.imsi, bts_uuid=bts_uuid, oldamt=self.balance, newamt=self.balance, change=0, reason='deactivated subscriber: %s' % self.imsi) event.save() for number in numbers: reason = 'deactivated phone number: %s' % number.number event = UsageEvent.objects.create( subscriber=self, date=now, bts=self.bts, kind='deactivate_number', to_number=number.number, reason=reason, oldamt=self.balance, newamt=self.balance, change=0) event.save() number.network = None number.subscriber = None number.state = 'available' number.save() # Actually delete the subscriber. Note that all associated # PendingCreditUpdates will be deleted automatically by the default # deletion CASCADE behavior. self.delete()
def create_many_to_many_intermediary_model(field, klass): from django.db import models def set_managed(model, related, through): through._meta.managed = model._meta.managed or related._meta.managed to_model = resolve_relation(klass, field.remote_field.model) name = '%s_%s' % (klass._meta.object_name, field.name) lazy_related_operation(set_managed, klass, to_model, name) to = make_model_tuple(to_model)[1] from_ = klass._meta.model_name if to == from_: to = 'to_%s' % to from_ = 'from_%s' % from_ meta = type(str('Meta'), (object,), { 'db_table': field._get_m2m_db_table(klass._meta), 'auto_created': klass, 'app_label': klass._meta.app_label, 'db_tablespace': klass._meta.db_tablespace, 'unique_together': (from_, to), 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, 'verbose_name_plural': _('%(from)s-%(to)s relationships') % {'from': from_, 'to': to}, 'apps': field.model._meta.apps, }) # Construct and return the new class. return type(str(name), (models.Model,), { 'Meta': meta, '__module__': klass.__module__, from_: models.ForeignKey( klass, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), to: models.ForeignKey( to_model, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ) })