unknown29
unknown29

Reputation: 47

Setting default value of field in model to another model instance

Model

class SlackPermission(models.Model):
    #fields

class GithubPermission(models.Model):
    #fields

class Employee(models.Model):
    #fields
    slack_permission = models.OneToOneField(SlackPermission, on_delete=models.CASCADE, related_name='Slack',default=SlackPermission.objects.get(pk=1))
    github_permission = models.OneToOneField(GithubPermission, on_delete=models.CASCADE, related_name='Github',default=GithubPermission.objects.get(pk=1))

Error:

ValueError: Cannot serialize: <GithubPermission: GithubPermission object (1)>
There are some values Django cannot serialize into migration files.

I am creating API just to create Employee. Where there is not option of giving slackpermissions and githubpermissions. How do I give default value in there?

Upvotes: 1

Views: 917

Answers (2)

jcirni
jcirni

Reputation: 57

The issue here is that you are attempting to set a field value to an object instance. So your default value should be just 1 if you are certain of the pk.

Also, I am not sure the advantage of creating two separate models for these permission values. Seems like they can just be fields in your employee model. Seems like these permissions share identical fields as well which will allow you to flatten them a bit.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

The problem is that the default is calculated immediately, and for migrations, it can not really serialize that.

That bing said, it is not very useful to do this anyway. You can just pass the primary key as default value. This is specified in the documentation on the default=… parameter [Django-doc]:

For fields like ForeignKey that map to model instances, defaults should be the value of the field they reference (pk unless to_field is set) instead of model instances.

So we can write this as:

class Employee(models.Model):
    full_name = models.CharField(max_length=100)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    slack_permission = models.OneToOneField(
        SlackPermission,
        on_delete=models.CASCADE,
        related_name='Slack',
        default=1
    )
    github_permission = models.OneToOneField(
        GithubPermission,
        on_delete=models.CASCADE,
        related_name='Github',
        default=1
    )

Note that you should ensure that there exists an object with that primary key. Therefore it might not be ideal to do that.

Upvotes: 1

Related Questions