[Answered ]-Django AttributeError: type object 'User' has no attribute '_collect_sub_objects'

2👍

Looking at the django source code, _collect_sub_objects was removed somewhere between release 1.2 and 1.3. See the changes.


Django now has an on_delete option for ForeignKeys, docs.

ForeignKey.on_delete

When an object referenced by a ForeignKey is deleted, Django by
default emulates the behavior of the
SQL constraint ON DELETE CASCADE and
also deletes the object containing the
ForeignKey. This behavior can be
overridden by specifying the on_delete
argument. For example, if you have a
nullable ForeignKey and you want it to
be set null when the referenced object
is deleted:

user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)

The possible values for on_delete are
found in django.db.models:

  • CASCADE: Cascade deletes; the default.

  • PROTECT: Prevent deletion of the referenced object by raising django.db.models.ProtectedError, a subclass of django.db.IntegrityError.

  • SET_NULL: Set the ForeignKey null; this is only possible if null is True.

  • SET_DEFAULT: Set the ForeignKey to its default value; a default for the ForeignKey must be set.

  • SET(): Set the ForeignKey to the value passed to SET(), or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported:

    def get_sentinel_user():
        return User.objects.get_or_create(username='deleted')[0]
    
    class MyModel(models.Model):
        user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))
    
  • DO_NOTHING: Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add a SQL ON DELETE constraint to the database field (perhaps using initial sql).

👤dting

Leave a comment