Heritage in Django models

2

In Django models, when you create a class that inherits from another that is not abstract, for database purposes, it's like creating a one-to-one relationship between the two tables.

Starting from the following      example:

class A(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=20)

class A1(A):
    other_field = models.CharField(max_length=20)


object_a_1 = A1.objects.create(name="test1", other_field="test2")

object_a = A.objects.get(id=object_a_1.a_ptr_id)

print object_a_1.a_ptr == object_a

My question is, is there a way to create the relationship between A1 and A in reverse? that is to say,     Starting from model A and then creating A1?

I give an example of what I would look for to achieve the same result as the previous example.

Could it be a valid option? What could be the correct way?

object_a = A.objects.create(name="test1")

object_a_1 = A1.objects.create(a_ptr=object_a, other_field="test2")

In this case, it would not work because when you create object_a_1 it returns

  

IntegrityError: NOT NULL constraint failed: models_a.timestamp

    
asked by Avara 15.09.2016 в 13:42
source

2 answers

1

When you use inheritance in django's model, you inherit the fields, not the object. Let me explain, you class A1 now have 3 fields the own (other_field) + 2 of A (timestamp, name) , so when creating the object A1 you must pass the 3 values, good 2 since timestamp es auto_add

object_a_1 = A1.objects.create(other_field="test2", name="test2")

If you use an object of another class to create A1 what you are trying to do is a relationship.

    
answered by 18.10.2016 в 15:18
0

Did you run migrations? Django by default would not pick up changes in the models. On the other hand, if you do not specify null=True , blank=True , it becomes a required field

Try this

timestamp = models.DateTimeField(auto_now_add=True, blank=True, null = True) 
    
answered by 15.09.2016 в 15:55