How does django assign a foreign key when using the create method of the associated object manager?

How does Django assign a foreign key when using a create

bound object manager method ?

I ask because when I create my own method create

, the foreign key is not automatically set.

Here's 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

      

+3


source to share


1 answer


Try this on your fifth line:



return super(ModelAQuery, self).create(**kwargs)

      

0


source







All Articles