kasia
kasia

Reputation: 298

Django: create new user with field which has ManyToMany relationship

Hi as I’m quite newby I’m trying to create a new user with ManyToMany relationship on account field:

models.py

    class User(AbstractBaseUser, PermissionMixin):
        id = models.UUIDField(primary_key=True)
        name = models.CharField(max_length=250),
        account = models.ManyToManyField(
          'accounts.Account',
          'through=’Membership'
        )

    class Account(models.Model):
        id = models.UUIDField(primary_key=True)
        name =  models.CharField(max_length=250),

    class Membership(models.Model):
        id = models.UUIDField(primary_key=True)
        account = models.ForeignKey(‘accounts.Account’)
        permissions = models.ManyToManyField(‘accounts.Role’)

What I need to achieve is after creating a new user the data from the api, I need to get this JSON:

{
    id: 1,
    name: 'User 1',
    accounts: [
        {
            id: 1,
            name: 'account1',
            permissions: [
                {
                    id: 1,
                    name: 'permission1'
                }
            ]
        },
        {
            id: 2,
            name: 'account2',
            permissions: [
                    {
                         id: 1,
                         name: 'permission'
                    },
                    {
                        id: 2,
                        name: 'permission2'
                    }
            ]
        }
    ]
}

So far I have only this and Im wondering how to deal with account with MAnyToMany relationship...

user = models.User.objects.create_user(
name='user 2',
accounts= ????
)

```’

Do I need to pass an array with accounts ids? but then how I can set the permission ? …

Thanks in advanced!!

Upvotes: 0

Views: 267

Answers (1)

Tom Wojcik
Tom Wojcik

Reputation: 6179

There are a few things to unpack here.

  1. You can, and probably should, create user and add user to accounts in two separate steps. Though if you want to do it in one step, just create a custom manager and wrap a few DB statements in a transaction.

  2. I am guessing that by PermissionMixin you meant PermissionsMixin from django.contrib.auth.models. Notice it adds groups and later on you add permissions to groups and users to groups. So it might already provide you with what you need.

  3. When you create m2m through, it has to have fk to both models. So here Membership needs to have a fk to both User and Account.

  4. How to create a m2m entity (fe. in you custom manager) is explained in the docs.

  5. There are already existing libraries for more complicated permissions than the ones Django comes with. Don't try to reinvent the wheel if you don't need to.

Upvotes: 1

Related Questions