Django | Automatic creation of objects in the model
I have two models 'CardsDesk' and 'Card'.
Example:
class CardsDesk(models.Model):
name = models.CharField(max_length=255, verbose_name='Название колоды', blank=True, null=True)
image = models.ImageField(upload_to='media/',verbose_name='Картинка колоды')
class Card(models.Model):
CHOICES = [
('Мечи', (
('Swords_1', 'Туз мечей'),
('Swords_2', 'Двойка мечей'),
('Swords_3', 'Тройка мечей'),
('Swords_4', 'Четверка мечей'),
('Swords_5', 'Пятерка мечей'),
('Swords_6', 'Шестерка мечей'),
('Swords_7', 'Семерка мечей'),
('Swords_8', 'Восьмерка мечей'),
('Swords_9', 'Девятка мечей'),
('Swords_10', 'Десятка мечей'),
('Swords_11', 'Паж мечей'),
('Swords_12', 'Рыцарь мечей'),
('Swords_13', 'Королева мечей'),
('Swords_14', 'Король мечей'),
)
),
............
I need that when I create a Model of type "CardDeck" Automatically create 78 objects with automatically selected categories.
Any ideas?
I tried the for loop, I tried the def save create(). So far I have absolutely no idea how to implement it.
Do it using Django Signals.
Assuming the following models in models.py
:
CARD_TYPE_CHOICES = [
('Swords_1', 'Туз мечей'),
('Swords_2', 'Двойка мечей'),
('Swords_3', 'Тройка мечей'),
('Swords_4', 'Четверка мечей'),
('Swords_5', 'Пятерка мечей'),
]
class CardDeck(models.Model):
name = models.CharField(max_length=255, verbose_name='Название колоды', blank=True, null=True)
image = models.ImageField(upload_to='media/',verbose_name='Картинка колоды')
class Card(models.Model):
deck = models.ForeignKey(CardDeck, on_delete=models.CASCADE)
card_type = models.CharField(default="Swords_1", choices=CARD_TYPE_CHOICES, max_length=32)
Create a file signals.py
with the following receiver for post_save
event of the CardDeck
model:
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import CardDeck, Card, CARD_TYPE_CHOICES
@receiver(post_save, sender=CardDeck)
def create_cards_for_deck(sender, instance, created, **kwargs):
if created:
cards = (Card(card_type=card_type[0], deck=instance) for card_type in CARD_TYPE_CHOICES)
Card.objects.bulk_create(cards)
Finally, bind the signals to your apps.py
file like:
from django.apps import AppConfig
class AppnameConfig(AppConfig):
name = 'appname'
def ready(self):
import appname.signals
Read more about bulk_create() method.