开发者

Django: Is it a good idea to use an abstract base model in this situation?

开发者 https://www.devze.com 2022-12-17 07:40 出处:网络
class Account(models.Model): identifier = models.CharField(max_length=5) objects = MyCustomManager() class开发者_如何转开发 Meta:
class Account(models.Model):
        identifier = models.CharField(max_length=5)
        objects = MyCustomManager()

        class开发者_如何转开发 Meta:
            abstract = True

class Customer(Account):
        name = models.CharField(max_length=255)

If I have a lot of models, and I want to save time from having to put foreignkeys everywhere, is this right? Or, am I thinking of this all wrong?


It depends in which direction the foreign keys go. You cannot have a foreign key to an abstract class.

Maybe it is Generic Relations what is interesting for you or foreign keys in abstract model classes.

Although notice that inheritance is always a is-a relationship while a normal foreign key usage implies a has-a relationship.

In your example, Customer should not inherit from Account as a customer has an account.

An inheritance example would be a Place which is either a Restaurant or a Cinema etc.

Edit after comment:

Well, there is a own section for this in the documentation:

Class inheritance and model managers aren't quite a perfect match for each other. Managers are often specific to the classes they are defined on and inheriting them in subclasses isn't necessarily a good idea. Also, because the first manager declared is the default manager, it is important to allow that to be controlled. So here's how Django handles custom managers and model inheritance:

...

  • Managers from abstract base classes are always inherited by the child class, using Python's normal name resolution order (names on the child class override all others; then come names on the first parent class, and so on). Abstract base classes are designed to capture information and behavior that is common to their child classes. Defining common managers is an appropriate part of this common information.
  • The default manager on a class is either the first manager declared on the class, if that exists, or the default manager of the first abstract base class in the parent hierarchy, if that exists. If no default manager is explicitly declared, Django's normal default manager is used.

I would only do if the inherited classes belong somehow to the same scope.
If you really a so many classes that it matters to add one line to these classes then you probably have not a good DB or application design.

And try not to put everything in one manager just to be able to use only one manager in a lot classes.


In this case you'll have 1 table for customer with account ID and if you'll add Worker he'll have his own table with account ID.

I think you probably want to have single table with accounts and attached objects customers, workers etc? This way you'll never mix-up your accounts.

0

精彩评论

暂无评论...
验证码 换一张
取 消