10 examples of 'django delete all objects' in Python

Every line of 'django delete all objects' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
192def _soft_delete(self, using=None, keep_parents=False, undelete=False):
193 items = self._collect_related(using=using, keep_parents=keep_parents)
194 deleted_counter = Counter()
195
196 required_pre_signal = models.signals.pre_delete
197 required_post_signal = models.signals.post_delete
198 required_status = BaseModel.STATUS_DELETED
199 required_deleted_at = timezone.now()
200
201 if undelete:
202 required_pre_signal = pre_undelete
203 required_post_signal = post_undelete
204 required_status = BaseModel.STATUS_ONLINE
205 required_deleted_at = None
206
207 with transaction.atomic(using=using, savepoint=False):
208
209 # pre signal...
210 for model, obj in items.get('instances_with_model'):
211 if not model._meta.auto_created:
212 required_pre_signal.send(sender=model, instance=obj, using=using)
213
214 # fast deletes-ish
215 for queryset in items.get('fast_deletes'):
216 count = queryset.count()
217
218 if issubclass(queryset.model, BaseModelWithSoftDelete):
219 # this happens in database layer...
220 # try to mark as deleted if the model is inherited from
221 # BaseModelWithSoftDelete
222 count = queryset.update(status=required_status, deleted_at=required_deleted_at)
223 else:
224 # well, just delete it...
225 count = queryset._raw_delete(using=using)
226 deleted_counter[queryset.model._meta.label] += count
227
228 for model, instances in items.get('data').items():
229 pk_list = [obj.pk for obj in instances]
230 queryset = model.objects.filter(id__in=pk_list)
231 count = queryset.count()
232
233 if issubclass(model, BaseModelWithSoftDelete):
234 count = queryset.update(status=required_status, deleted_at=required_deleted_at)
235
236 deleted_counter[model._meta.label] += count
237
238 if not model._meta.auto_created:
239 for obj in instances:
240 required_post_signal.send(sender=model, instance=obj, using=using)
241
242 return sum(deleted_counter.values()), dict(deleted_counter)
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

25def delete_django_app_permissions(sender, **kwargs):
26 """
27 Deletes the permissions, Django creates by default. Only required
28 for auth, contenttypes and sessions.
29 """
30 contenttypes = ContentType.objects.filter(
31 Q(app_label="auth") | Q(app_label="contenttypes") | Q(app_label="sessions")
32 )
33 Permission.objects.filter(content_type__in=contenttypes).delete()
213def delete(self):
214 cache_el = None
215 for el in self:
216 cache_el = el.delete(renew=False)
217 if cache_el:
218 cache_el.renew_cache()
239def related_objects(self, related, objs):
240 """
241 Gets a QuerySet of objects related to ``objs`` via the relation ``related``.
242
243 """
244 return related.related_model._base_manager.using(self.using).filter(
245 **{"%s__in" % related.field.name: objs}
246 )
17def delete_obj(self, request, querysets):
18 querysets.delete()
128def get_deleted_objects(objs, opts, user, admin_site, using):
129 """
130 Find all objects related to ``objs`` that should also be deleted. ``objs``
131 must be a homogeneous iterable of objects (e.g. a QuerySet).
132
133 Returns a nested list of strings suitable for display in the
134 template with the ``unordered_list`` filter.
135 """
136 collector = NestedObjects(using=using)
137 collector.collect(objs)
138 perms_needed = set()
139
140 def format_callback(obj):
141 has_admin = obj.__class__ in admin_site._registry
142 opts = obj._meta
143
144 no_edit_link = '%s: %s' % (capfirst(opts.verbose_name),
145 force_text(obj))
146
147 if has_admin:
148 try:
149 admin_url = reverse('%s:%s_%s_change'
150 % (admin_site.name,
151 opts.app_label,
152 opts.model_name),
153 None, (quote(obj._get_pk_val()),))
154 except NoReverseMatch:
155 # Change url doesn't exist -- don't display link to edit
156 return no_edit_link
157
158 p = '%s.%s' % (opts.app_label,
159 get_permission_codename('delete', opts))
160 if not user.has_perm(p):
161 perms_needed.add(opts.verbose_name)
162 # Display a link to the admin page.
163 return format_html('{}: <a href="{}">{}</a>',
164 capfirst(opts.verbose_name),
165 admin_url,
166 obj)
167 else:
168 # Don't display link to edit, because it either has no
169 # admin or is edited inline.
170 return no_edit_link
171
172 to_delete = collector.nested(format_callback)
173
174 protected = [format_callback(obj) for obj in collector.protected]
175 model_count = {model._meta.verbose_name_plural: len(objs) for model, objs in collector.model_objs.items()}
176
177 return to_delete, model_count, perms_needed, protected
24def remove_objects_not_in(self, objects_to_keep, verbosity):
25 """
26 Deletes all the objects in the database that are not in objects_to_keep.
27 - objects_to_keep: A map where the keys are classes, and the values are a
28 set of the objects of that class we should keep.
29 """
30 for class_ in objects_to_keep.keys():
31 current = class_.objects.all()
32 current_ids = set([x.id for x in current])
33 keep_ids = set([x.id for x in objects_to_keep[class_]])
34
35 remove_these_ones = current_ids.difference(keep_ids)
36 if remove_these_ones:
37 for obj in current:
38 if obj.id in remove_these_ones:
39 obj.delete()
40 if verbosity >= 2:
41 print("Deleted object: %s" % six.u(obj))
42
43 if verbosity > 0 and remove_these_ones:
44 num_deleted = len(remove_these_ones)
45 if num_deleted > 1:
46 type_deleted = six.u(class_._meta.verbose_name_plural)
47 else:
48 type_deleted = six.u(class_._meta.verbose_name)
49
50 print("Deleted %s %s" % (str(num_deleted), type_deleted))
165def get_deleted_objects(self, objs, user, using='default'):
166 """
167 Find all objects related to ``objs`` that should also be deleted. ``objs``
168 must be a homogeneous iterable of objects (e.g. a QuerySet).
169
170 Return a nested list of strings suitable for display in the
171 template with the ``unordered_list`` filter.
172
173 Encontre todos os objetos relacionados a ``objs`` que também devem ser deletados. ``objs``
174         deve ser um iterável homogêneo de objetos (por exemplo, um QuerySet).
175
176         Retornar uma lista aninhada de sequências adequadas para exibição no
177         template com o filtro `` unordered_list``.
178 """
179 collector = NestedObjects(using=using)
180 collector.collect(objs)
181 perms_needed = set()
182
183 def format_callback(obj):
184 opts = obj._meta
185
186 no_edit_link = '%s: %s' % (str(opts.verbose_name).title(), obj)
187
188 try:
189 url = reverse('%s:%s-update'% (
190 opts.app_label,
191 opts.model_name),
192 None, (quote(obj.pk),))
193
194
195 except NoReverseMatch:
196 # Change url doesn't exist -- don't display link to edit
197 return no_edit_link
198
199 p = '%s.%s' % (opts.app_label, get_permission_codename('delete', opts))
200 if not user.has_perm(p):
201 perms_needed.add(opts.verbose_name.title())
202 # Display a link to the admin page.
203 return format_html('{}: <a href="{}">{}</a>',
204 str(opts.verbose_name).title(),
205 url,
206 obj)
207
208 to_delete = collector.nested(format_callback)
209
210 protected = [format_callback(obj) for obj in collector.protected]
211 model_count = {model._meta.verbose_name_plural: len(objs) for model, objs in collector.model_objs.items()}
212
213 return perms_needed, protected
87@receiver(post_delete)
88def on_post_delete(sender, **kwargs):
89 """Expire ultracache cache keys affected by this object
90 """
91 if not invalidate:
92 return
93 if kwargs.get("raw", False):
94 return
95 if sender is MigrationRecorder.Migration:
96 return
97 if issubclass(sender, Model):
98 obj = kwargs["instance"]
99 if isinstance(obj, Model):
100 # get_for_model itself is cached
101 try:
102 ct = ContentType.objects.get_for_model(sender)
103 except RuntimeError:
104 # This happens when ultracache is being used by another product
105 # during a test run.
106 return
107
108 # Expire cache keys
109 key = "ucache-%s-%s" % (ct.id, obj.pk)
110 to_delete = cache.get(key, [])
111 if to_delete:
112 try:
113 cache.delete_many(to_delete)
114 except NotImplementedError:
115 for k in to_delete:
116 cache.delete(k)
117 cache.delete(key)
118
119 # Invalidate paths in reverse caching proxy
120 key = "ucache-pth-%s-%s" % (ct.id, obj.pk)
121 if purger is not None:
122 for path in cache.get(key, []):
123 purger(path)
124 cache.delete(key)
165def delete(self, *args, **kwargs):
166 res = super(CachedQuerySet, self).delete(*args, **kwargs)
167 model_change(collection=self._document._get_collection_name())
168 return res

Related snippets