0

I want to create a model within the save method of another model, so the one generated dynamically is named with a field from the static model.

Model Code:

class Car(models.Model):
    name = models.CharField(max_length=128)

    def save(self, *args, **kwargs):
        attrs = {
            'piece': models.CharField(max_length=128),
            '__module__': 'myapp.models'
        }
        model = type('%s_piece' % self.name, (models.Model,), attrs)
        admin.site.register(model)
        super(Car, self).save(*args, **kwargs)

The model is generated but I don't know how to make the migrations or migrate it to the database.

I tried to migrate it with:

from django.core.management import call_command
call_command('makemigrations')
call_command('migrate')

But I get an error as I'm executing this in an atomic transaction.

Jose M Martin
  • 373
  • 1
  • 3
  • 19
  • Why would you do this? What's the point? How would you go about referencing this new model outside that method? Really, don't. – Daniel Roseman Jan 15 '19 at 15:48
  • @DanielRoseman the problem is I have a huge amount of pieces to put them all in a single model, so I wanted to split them by car model – Jose M Martin Jan 15 '19 at 15:50
  • I tried and worked fine. Can you give a sample generated model? and which error show – shafik Jan 15 '19 at 15:50
  • you can do it by post_save() signal refer this https://stackoverflow.com/questions/13014411/django-post-save-signal-implementation – Yugandhar Chaudhari Jan 15 '19 at 15:51
  • 2
    You can generate the migrations, but once you leave that `save` method `model` goes out of scope. Now you have no way of referencing that attribute; the generated class just disappears. So what's the point? – Daniel Roseman Jan 15 '19 at 15:53
  • @ShafikurRahman how did you migrate the model into the database – Jose M Martin Jan 15 '19 at 15:53
  • @DanielRoseman yes I get that, so how would you store the pieces? All into the same model will make the load really slow... – Jose M Martin Jan 15 '19 at 16:01
  • Why would it be slow? If you have a Piece model with a ForeignKey to Car, each car would only load the pieces that belonged to it. – Daniel Roseman Jan 15 '19 at 16:04

0 Answers0