gpt4 book ai didi

python - Django 在创建另一个对象时创建并保存模型的许多实例

转载 作者:行者123 更新时间:2023-11-28 21:41:44 24 4
gpt4 key购买 nike

我正在设计一个国际象棋游戏,我想在新的 ChessParty 开始后用棋子(状态模型)初始化字段。
我阅读了有关覆盖 save() 模型方法的信息,但我不知道如何在我的案例中使用它。
我正在阅读有关 post_save 之类的信号,但我遇到了同样的问题。

这样的东西能行吗?

    def save(self, *args, **kwargs):
(Here i want create many instances of another Model)
super(ChessParty, self).save(*args, **kwargs)

到目前为止,这是我的代码:

class ChessParty(models.Model):
chessparty_id = models.AutoField("ID partii", primary_key=True)
arbiter = models.ForeignKey(Arbiter, related_name='sedzia',
verbose_name="Sędzia")
white = models.ForeignKey(Player, related_name='Białe',
verbose_name="Białe figury")
black = models.ForeignKey(Player, related_name='Czarne',
verbose_name="Czarne figury")
tournament = models.ForeignKey(Tournament, verbose_name="Nazwa turnieju")

def __str__(self):
return "{white} vs {black}, ({tournament})"\
.format(black=self.black, white=self.white, tournament=self.tournament)


class OneMove(models.Model):
party = models.ForeignKey(ChessParty, default='0', verbose_name="Partia")
chessman = (
('a1_w_rook', 'biała wieża a1'), ('h1_w_rook', 'biała wieża h1'),
('b1_w_knight', 'biały skoczek b1'), ('g1_w_knight', 'biały skoczek g1'),
('c1_w_bishop', 'biały goniec c1'), ('f1_w_bishop', 'biały goniec f1'),
('d1_w_queen', 'biały hetman d1'), ('e1_w_king', 'biały król e1'),
('a2_w_pawn', 'biały pion a2'), ('b2_w_pawn', 'biały pion b2'),
('c2_w_pawn', 'biały pion c2'), ('d2_w_pawn', 'biały pion d2'),
('e2_w_pawn', 'biały pion e2'), ('f2_w_pawn', 'biały pion f2'),
('g2_w_pawn', 'biały pion g2'), ('h2_w_pawn', 'biały pion h2'),
('a8_b_rook', 'czarna wieża a1'), ('h8_b_rook', 'czarna wieża h8'),
('b8_b_knight', 'czarny skoczek b1'), ('g8_b_knight', 'czarny skoczek g8'),
('c8_b_knight', 'czarny goniec c1'), ('f8_b_bishop', 'czarny goniec f8'),
('d8_b_queen', 'czarny hetman d1'), ('e8_b_king', 'czarny król e8'),
('a7_b_pawn', 'czarny pion a7'), ('b7_b_pawn', 'czarny pion b7'),
('c7_b_pawn', 'czarny pion c7'), ('d7_b_pawn', 'czarny pion d7'),
('e7_b_pawn', 'czarny pion e7'), ('f7_b_pawn', 'czarny pion f7'),
('g7_b_pawn', 'czarny pion g7'), ('h7_b_pawn', 'czarny pion h7'),
)
chessman = models.CharField(max_length=30, choices=chessman, default='pionek', verbose_name="Figura Szachowa")
mymove = []
for a, b in itertools.product('abcdefgh', '12345678'):
name = a + b
mymove.append((name, name))
mytuple = tuple(mymove)
move = models.CharField(max_length=2, choices=mytuple, default='a1', verbose_name="Ruch na")

class Meta:
abstract = True


class State(OneMove):
state_id = models.PositiveIntegerField(default=0, verbose_name="numer ruchu")
is_capture = models.BooleanField(default=False, verbose_name="Czy zbita")
capture_choice = (
('true', 'zbity'),
('false', 'nie zbity'),
)
is_capture = models.CharField(max_length=9, choices=capture_choice, default='false', verbose_name="Czy zbity")

最佳答案

使用save():

如果您想使用save() 方法,您可以执行以下操作:

def save(self, *args, **kwargs):
OtherModel.objects.create(something=kwargs['something'])
YetAnotherModel.objects.create(
something_else=kwargs['something_else']
)
super(ChessParty, self).save(*args, **kwargs)

正如@e4c5 在他的评论中所说,它更容易实现,这就是我将它包括在内的原因!


我对这个问题的看法:

尽管您可以在 save() 上执行此操作,但我建议改为使用 signal .

具体使用一个post_save信号。以下是如何做到这一点:

  1. 创建文件 your_app/signals.py:

    from django.db.models.signals import post_save
    from django.dispatch import receiver

    from your_app.models import ChessParty, OtherModel, YetAnotherModel


    @receiver(post_save, sender=ChessParty)
    def change_my_name_plz (sender, instance, created, **kwargs):
    if created:
    OtherModel.objects.create(something=kwargs['something'])
    YetAnotherModel.objects.create(
    something_else=kwargs['something_else']
    )
  2. 您现在需要覆盖 your_app/app.py 上的 ready() 函数:

    from django.apps import AppConfig

    class YourAppConfig(AppConfig):
    name = 'your_project.your_app'

    def ready(self):
    import your_project.your_app.signals
  3. 最后,在your_app/__init__.py中添加以下内容:

    default_app_config = 'your_project.your_app.apps.YourAppConfig'

现在您有一个信号,它将在您创建一个新的 ChessParty 对象后立即创建一个 OtherModelYetAnotherModel 对象。


定义信号的替代方法:

还有一种替代方法不使用 @receiver 装饰器,而是使用 connect()方法:

  1. your_app/signals.py:

    from your_app.models import ChessParty, OtherModel, YetAnotherModel


    def change_my_name_plz (sender, instance, created, **kwargs):
    if created:
    OtherModel.objects.create(something=kwargs['something'])
    YetAnotherModel.objects.create(
    something_else=kwargs['something_else']
    )
  2. your_app/app.py:

    from django.apps import AppConfig
    from django.db.models.signals import post_save

    from your_app.models import ChessParty
    from your_project.your_app.signals import change_my_name_plz

    class YourAppConfig(AppConfig):
    name = 'your_project.your_app'

    def ready(self):
    post_save.connect(change_my_name_plz, sender=ChessParty)
  3. your_app/__init__.py 与上面相同(第 3 步)。


关于python - Django 在创建另一个对象时创建并保存模型的许多实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44451771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com