Django ORM: add parent class and access its class variable from children

吃可爱长大的小学妹 提交于 2021-01-29 13:33:02

问题


I am working on a restaurant app (and new to Django/Python). I want to have a parent class Dish that will contain some counter or ID that increments for every instance of a child class of Dish. The instances are dishes like Pizza, Pasta, etc with different characteristics. I've tried making Dish abstract and non-abstract, but come across different issues each time.

This is my Dish class (to make it abstract I tried InheritanceManager(), but ran into complications there that led me to think it's overkill for my simple purposes. Non-abstract, kept giving me You are trying to add a non-nullable field 'pasta_ptr', followd by IntegrityError: UNIQUE constraint failed):

class Dish(models.Model):
  #objects = InheritanceManager()
  counter = models.PositiveIntegerField(default=0)

  class Meta:
        abstract = True

This is an example of a child class - I'd like every pasta-entry to get its own Dish-ID or counter on the menu - like a class attribute in Python. How do I access and implement this from the child class? If Dish is not abstract, can I use (& access) Dish's primary key that will tie each dish to my desired ID?

class Pasta(Dish):
  #Dish.counter +=1
  name = models.CharField(max_length=64, primary_key=True)
  price = models.DecimalField(max_digits=6, decimal_places=2)

  def __str__(self):
    return f"{self.name}, price: ${self.price}"

来源:https://stackoverflow.com/questions/60948986/django-orm-add-parent-class-and-access-its-class-variable-from-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!