Population models from other models in Django?

This is somewhat related to the question asked in this question , but I'm trying to do this with an abstract base class.

For the purposes of this example, the following models can be used:

class Comic(models.Model):
    name = models.CharField(max_length=20)
    desc = models.CharField(max_length=100)
    volume = models.IntegerField()
    ... <50 other things that make up a Comic>

    class Meta:
        abstract = True

class InkedComic(Comic):
    lines = models.IntegerField()

class ColoredComic(Comic):
    colored = models.BooleanField(default=False)

In the let say view, we get a link to InkedComic id, since tracer, err, I mean, inker is done by drawing lines, and this is the time to add color. After the view has added all the color, we want to save it ColoredComicin db.

Obviously we could do

inked = InkedComic.object.get(pk=ink_id)
colored = ColoredComic()
colored.name = inked.name
etc, etc.

But actually it would be nice to do:

colored = ColoredComic(inked_comic=inked)
colored.colored = True
colored.save()

I tried to do

class ColoredComic(Comic):
    colored = models.BooleanField(default=False)

    def __init__(self, inked_comic = False, *args, **kwargs):
        super(ColoredComic, self).__init__(*args, **kwargs)
        if inked_comic:
            self.__dict__.update(inked_comic.__dict__)
            self.__dict__.update({'id': None}) # Remove pk field value

but it turns out that the call ColoredComic.objects.get(pk=1)puts pkin a keyword inked_comicthat is clearly not intended. (and actually results in intno exception dict)

, - ?

+3
2

?

colored = ColoredComic.create_from_Inked(pk=ink_id)
colored.colored = True
colored.save()

, - ( )

class ColoredComic(Comic):
    colored = models.BooleanField(default=False)

    @staticmethod
    def create_from_Inked(**kwargs):
        inked = InkedComic.objects.get(**kwargs)
        if inked:
            colored = ColoredComic.objects.create()
            colored.__dict__.update(inked.__dict__)
            colored.__dict__.update({'id': None}) # Remove pk field value
            return colored
        else:
            # or throw an exception...
            return None
+3

:

inked = InkedComic.object.get(pk=ink_id)
inked.__class__ = ColoredComic
inked.colored = True
inked.save()
0

Source: https://habr.com/ru/post/1741165/


All Articles