Search code examples
pythondjangoshelldjango-modelsrevitpythonshell

How can I add a new record with multiple actie_gebruiker(s) via the Python shell?


Here are the imports:

from django.db import models
from datetime import datetime, timedelta
from django.contrib.auth.models import User

This is the first class I defined. It is the status of the action (Actie) and it has a status-id and a status-name with a max_length attribute of 5 (todo, doing, done)

class Status(models.Model):
    id = models.IntegerField(primary_key=True)
    status_naam = models.CharField(max_length=5, default='todo')

    def __str__(self):
        return str(self.id) + " - " + self.status_naam

This is the class Actie (Action or the action the user determines) which has an id, an action-name, a action-status which refers to the table Status here above, an action-publish-date, an ending-date (the deadline) and a user-id which refers to the table Users django gives me.

class Actie(models.Model):
    id = models.IntegerField(primary_key=True)
    actie_naam = models.CharField(max_length=150, default='-')
    actie_status = models.ForeignKey(Status, default=1)
    actie_aanmaakdatum = models.DateTimeField(default=datetime.now())
    actie_einddatum = models.DateTimeField(default=datetime.now() + timedelta(days=1))
    actie_gebruiker = models.ManyToManyField(User)

    def __str__(self):
        return str(self.id) + " - " + self.actie_naam

My question now is how can I add a new Actie-object with multiple actie_gebruiker(s) via the Python shell like what command do I have to use?


Solution

  • You can use add method from a ManyToManyField field relation to add objects. Take a look to the Django documentation for ManyToManyField

    actie = Actie.objects.create() # put some parameters inside create
    user1 = # get or create user
    actie.actie_gebruiker.add(user1)
    user2 = # get or create user
    actie.actie_gebruiker.add(user2)