3

How does Django assign the foreign key when using the create method of a related object manager?

I'm asking because when I create my own create method, the foreign key is not set automatically.

Here is an example:

class ModelAQuerySet(models.QuerySet):
    def create(self, **kwargs):
        print('create:')
        print(kwargs)
        return super().create(**kwargs)

    def create_with_other_options(self, **kwargs):
        print('create_with_other_options:')
        print(kwargs)
        return self.create(**kwargs)

class ModelABaseManager(models.Manager):
    use_for_related_fields = True    

ModelAManager = ModelABaseManager.from_queryset(ModelAQuerySet)

class ModelA(models.Model):
    objects = ModelAManager()
    user = models.ForeignKey('User', related_name='modela_set')

When I use the methods:

>>> u = User.object.get(...)
>>> a1 = u.modela_set.create() # it works, user is set automatically
create:
{..., 'user': <User: id:1 email:"...">}

>>> a2 = u.modela_set.create_with_other_options() # it does not work, user is not set automatically
create_with_other_options:
{}
IntegrityError: null value in column "user_id" violates not-null constraint
Michael
  • 8,357
  • 20
  • 58
  • 86

1 Answers1

0

Try with this on your 5th line:

return super(ModelAQuery, self).create(**kwargs)
Eric Acevedo
  • 1,182
  • 1
  • 11
  • 26