我有一个带有ManyToManyField的模型,并希望在创建该模型时从其他表中添加所有数据。 这是我到目前为止所获得的代码,它不保存条目:
'''
Klassendefinition für den Spieltag
'''
from django.db import models
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.models import TimeStampedModel
from season.models import Season
from player.models import Player
# Create your models here.
class Matchday(TimeStampedModel):
'''
Klasse für den Spieltag
'''
seasontable = models.ManyToManyField("table.Table", related_name="Ligaspieltisch", blank=True)
matchtable = models.ManyToManyField("table.Table", related_name="Pfeilsystemtisch", blank=True)
#Spieler die am Spieltag angemeldet sind (Kickereuro)
signedin = models.ManyToManyField("player.Player", related_name="Angemeldet", blank=True)
needtopay = models.BooleanField(_("Soll der Kickereuro gezahlt werden?"), default=True)
finished = models.BooleanField(_("Beendet?"), default=False)
season = models.ForeignKey(Season, verbose_name=_("Saison"), blank=True, null=True)
class Meta:
'''
Metaklasse für Spieltag
'''
verbose_name = _("Spieltag")
verbose_name_plural = _("Spieltage")
ordering = ('-created',)
def __str__(self):
return "Spieltag"
@receiver(models.signals.post_save, sender=Matchday)
def execute_after_save(sender, instance, created, *args, **kwargs):
'''
Ausführen, wenn matchday gespeichert wird
'''
if created: #Wurde matchday neu erstellt?
if not instance.needtopay:
#Kickereuro muss nicht gezahlt werden -> alle Spieler hinzufügen
instance.save()
players = Player.objects.all()
players = list(players)
for player in players:
instance.signedin.add(player)
instance.save()
players = instance.signedin.all()
print(players)
打印(播放器)用于调试目的并正确返回播放器列表,但不保存。 我在开始时没有 instance.save()和 instance.signedin.add(*播放器)尝试了它,两者都不起作用。 我在这里做错了什么?