Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a abstract model to another instance?

Tags:

django

I have the following situation:

class AbstractModel(models.Model):
    # fields

    class Meta:
        abstract = True

class A(AbstractModel):
    # no extra fields

class B(AbstractModel):
    # no extra fields

now i want to save one row from A to B, is there a easy way to do it? or do i need to copy every field on its own?

Also is there a better way in doing this? I need this, cause i have one table that could be modified by a user, but the other is frozen, from the frozen one i create pdfs, but when i change something in class A it shouldn't override something in class B, it should create a new instance of B.

like image 540
Christian Schmitt Avatar asked Mar 12 '26 07:03

Christian Schmitt


1 Answers

now i want to save one row from A to B, is there a easy way to do it? or do i need to copy every field on its own?

You can use the model_to_dict from django.forms to generate an initial kwargs dict:

from django.forms import model_to_dict
a = A.objects.get(..)
kwargs = model_to_dict(a)
kwargs.pop('id')
b = B.objects.create(**kwargs)
like image 196
tuxcanfly Avatar answered Mar 13 '26 22:03

tuxcanfly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!