I'm using multi table inheritance in django. Model Ninja inherits from Person. In my tests, I'm creating two Ninja instances and one Person instance. I'm doing:
self.assertEquals(Person.objects.count(), 3)
But count is 1. Why isn't it 3? I was under the impression that a Person table is created for every Ninja.
As per your description, a Ninja is a Person. Therefore, you have three Persons: 1 regular, 2 Ninja.
This is intended behavior. If you want to know the Persons who are not anything else (not Ninja, in your case), you have to explicitly ask the ORM for it. For example:
Person.objects.
exclude(id__in=Ninja.objects.values('id')).
exclude(id__in=SomeOtherPersonSubclass.objects.values('id'))
I'm not sure the code is correct/working, but I think it conveys the idea.
The fact that your database isn't behaving as expected (as you talked about in the comments) is because, in order to have a Ninja instance, it needs it Person "part", so to speak. You'd have to have something like:
[
{
"model": "myapp.person",
"pk": 1,
"fields": {
"first_name": "John",
"last_name": "Lennon"
}
},
{
"model": "myapp.person",
"pk": 2,
"fields": {
"first_name": "Hattori",
"last_name": "Hanzo"
}
},
{
"model": "myapp.ninja",
"pk": 2,
"fields": {
"super_power": "fearless tactics"
}
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With