[Django]-Assigning a proxy model instance to foreign key

1👍

Why are you calling your proxy class User, which is guaranteed to lead to confusion between that and django.contrib.auth.models.User? Why not UserProxy, or MyUser? Then it could be distinguished whenever you use it.

22👍

In addition to what @DavidRobinson said, you need to be careful about creating foreign keys to proxy models. A proxy model is still a subclass of the model it proxies, despite being for all intents and purposes the same as the model. If you have a foreign key to the proxy it will not accept the base class, however a foreign key to the base class will accept the the proxy. Take the following for example.

Given:

class UserProxy(User):
    class Meta:
        proxy = True
    ...

class User(models.Model):
    ...

The following will raise an exception:

class SomeModel(models.Model):
    user = models.ForeignKey(UserProxy)

user = User.objects.get(username='some_user')
instance = SomeModel.objects.create(user=user)

But, the following will work fine:

class SomeModel(models.Model):
    user = models.ForeignKey(User)

user = UserProxy.objects.get(username='some_user')
instance = SomeModel.objects.create(user=user)

This is due to the directionality of the relationship. UserProxy is-a User, but User is not a UserProxy.

0👍

Try to assign id instead of object

project = Project.objects.create(owner_id=request.user.pk)
👤San4ez

Leave a comment