简体   繁体   中英

Multi table inheritance in django

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"
    }
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM