Subclass for python and django

linkaiyi
Follow

Explanation of subclass

It is possible to create several subclass children with the same parent object. Primary key of subclass child is the same as the pk of the parent object.

Child object use parent_ptr field to refer to the parent object.

class Resource(models.model):
    pass

class HumanResource(Resource):
    pass

currency = Currency.objects.filter(description='EURO').first()
                user = User.objects.filter(first_name=first_name, last_name=last_name).first()
                # print(user)
                resource_type = ResourceType.objects.filter(title='Standard Beratung').first()
                if not resource_type:
                    resource_type = ResourceType.objects.create(title='Standard Beratung')

                human_resource, created = HumanResource.objects.get_or_create(user=user, resource_type=resource_type, rate_hour=100.00, default_currency=currency)

But the following example will only create one human resource object and rewrite everytime the same object is saved

resource, created = Resource.objects.get_or_create(resource_type=resource_type, rate_hour=100.00, default_currency=currency)
                if not resource:
                     resource = Resource.objects.create(resource_type=resource_type, rate_hour=100.00, default_currency=currency)
                 human_resource = HumanResource(user=user, resource_ptr=resource)
                 human_resource.save_base(raw=True) # if not using save_base, everytime human_resource is saved, a new resource object without any attributes will be created. (Null, null, null)
                # print(human_resource.id)
Object has 0 attachments

Was this article helpful?

This article is viewed 50 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support