【发布时间】:2016-08-09 23:33:58
【问题描述】:
序幕:
我有一些模型叫做:
- 主管
- 推销员
- 汽车
- 摩托车
- Product(汽车和摩托车的抽象模型)
推销员和主管可以销售汽车。主管还控制两个或多个销售人员的工作。
我该怎么办: 我想为该任务创建最合适的模型。
问题:
问题是主管可以控制销售人员并销售产品。我想创建一个名为'Staff' 的抽象模型,它将是Salesman 和Supervisor 之间的共享字段,Product 将有ForeignKey 到Staff。但我无法将ForeignKey 制作成抽象模型。
我不希望将Product 作为一个销售员字段或主管字段是否为空的表。而且我不想使用通用的ForeignKey,因为它太复杂了。
我的最佳猜测:添加 John Smith,例如,作为主管和推销员。在这种情况下,John Smith 推销员拥有 John Smith 主管的 ForeignKey。但我认为有最好的解决方案。
最简单但错误的决定。
class Product(models.Model):
company = models.ForeignKey(Company, verbose_name = 'Car company');
price = models.IntegerField()
horse_power = models.IntegerField()
salesman = models.ForeignKey(Salesman, null=True)
supervisor = models.ForeignKey(Supervisor, null=True)
class Meta:
abstract = True
class Car(Product):
number_of_doors = models.IntegerField()
is_conditioner = models.NullBooleanField()
class Supervisor(models.Model):
name = models.CharField(max_length=100)
class Salesman(models.Model):
name = models.ChartField(max_length=100)
supervisor = models.ForeignKey(Supervisor)
我的问题是,如果其中一个在每种情况下都为 NULL 并避免 ForeignKey 抽象模型,那么重写模型结构以避免两个 ForeignKeys 的最佳方法是什么。
【问题讨论】: