简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM