user1489223
user1489223

Reputation: 153

Handling M2M relationships in Django

I have a User model that extends the built in Django User model:

class CustomUser(User):
    objects = UserManager()
    tasks = models.ManyToManyField(Task)

I created a User in the shell using:

user=CustomUser.objects.create_user('fred', '[email protected]', 'fredpass')

I have another model for Tasks and as you can see CustomUser has a manytomanyfield relating it to Task.

How would I add and remove tasks that have already been created to be associated with the user I have created?

Upvotes: 1

Views: 59

Answers (1)

user1489223
user1489223

Reputation: 153

P=Project.objects.get(pk=1)
task=p.task_set.get(task_name='Task1')
user1=CustomUser.objects.get(username='john')
user1.tasks.add(task)

This was my solution

Upvotes: 1

Related Questions