在我的自定义命令文件中,我想向模型添加对象。这是我其中一个应用中的models.py
...
from wagtail.core.models import Page
from modelcluster.fields import ParentalKey, ParentalManyToManyField
class PersonPage(Page):
name = models.CharField("Name", max_length=255)
entity = models.ForeignKey("bids.EntityPage", null=True, on_delete=models.PROTECT)
class EntityPage(Page):
name = models.CharField("Name", max_length=255)
class BidPage(Page):
pre_bid_attendees = ParentalManyToManyField("bids.PersonPage", blank=True)
在我的custom_command.py
中,我有这个:
from django.core.management.base import BaseCommand, CommandError
from wagtail.core.utils import cautious_slugify
from bids.models import *
import os.path, csv
class Command(BaseCommand):
help = "Automate the insertion of pre-bid attendees using CSV file."
def add_arguments(self,parser):
parser.add_argument("--file")
def handle(self, *args, **options):
reader = csv.DictReader(open(options["file"]))
for row in reader:
if not EntityPage.objects.filter(name=row["Entity"]).exists():
parentEntityPage = EntityIndexPage.objects.first()
newEntity = EntityPage(
title=row["Entity"],
name=row["Entity"],
slug=cautious_slugify(row["Entity"]),
live=False,
)
parentEntityPage.add_child(instance=newEntity)
newEntity.save_revision(submitted_for_moderation=True)
self.stdout.write(self.style.SUCCESS("Added entity: '%s'" % row["Entity"]))
entityID = EntityPage.objects.get(name=row["Entity"]).page_ptr_id
if not PersonPage.objects.filter(entity_id=entityID, name=row["Name"]).exists():
parentPersonPage = PersonIndexPage.objects.first()
newPerson = PersonPage(
title=row["Name"],
entity_id=entityID,
live=False,
)
parentPersonPage.add_child(instance=newPerson)
newPerson.save_revision(submitted_for_moderation=True)
self.stdout.write(self.style.SUCCESS("Added person '%s' of entity '%s'" % (row["Name"],row["Entity"])))
我想构建一个自定义命令,该命令将从CSV读取数据并将数据插入数据库的bids_bidpage_pre_bid_attendees
表中。如何在BidPage
字段中与人一起向班级添加pre_bid_attendees
对象?