简体   繁体   English

如何在Django中建模(继承的模型,其中每个继承的模型都有唯一的方法)

[英]How to model this in django (inherited model, where each inherited model has a unique method)

How to model this in django: 如何在Django中建模:

1) have a base network of manufacturers 1)拥有制造商的基础网络

2) under each network their might be several distributors 2)在每个网络下,他们可能是几个分销商

3) a user of the system can access items through the distributor 3)系统的用户可以通过分销商访问商品

4) if a user access the item through the distributor we want that item to be translated where each manufacturer will have their own translation 4)如果用户通过分销商访问商品,我们希望该商品被翻译,每个制造商都有自己的翻译

class Manufacturer(models.Model):
    networkname = models.CharField(max_length=128)

    class Meta:
        proxy = True

class Distributor(models.Model):
    man = models.ForeignKey(Manufacturer)

class ManuType1(Manufacturer):
    def translate(self, str):
        return 'translate'

class ManuType2(Manufacturer):
    def translate(self, str):
        return 'translate'

In this scenario we will get a request for a certain Distributor. 在这种情况下,我们将请求某个分销商。 We identify that distributor and we want to call that distributors manufacturers translate method. 我们确定该分销商,并希望称其为分销商翻译方法。 Does this look like a way to model this in django (I'm sure there are many ways to do this) so any input/feedback is useful. 这看起来像是在Django中建模的方式(我敢肯定有很多方法可以做到这一点),所以任何输入/反馈都是有用的。

Where I run into problems (not knowing python well enough perhaps) is given a Distributor with ManuType1 How do I call the translate function at runtime? 我遇到问题的地方(也许不太了解python)被分配了ManuType1的Distributor。如何在运行时调用translate函数?

This is probably a well explored pattern using other terms, just not sure how to express it exactly. 这可能是使用其他术语的一种经过充分研究的模式,只是不确定如何准确地表达它。

If dist is an instance of Distributor, then you can do dist.man to get the Manufacturer instance. 如果dist是Distributor的实例,则可以执行dist.man来获取Manufacturer实例。 Due to the way multi-table inheritance works in Django, you'll need to access the OneToOneField that exists on the Manufacturer to the subclass instance. 由于多表继承在Django中的工作方式,您需要将Manufacturer上存在的OneToOneField访问到子类实例。 The problem lies in figuring out which subclass instance exists. 问题在于找出哪个子类实例存在。 This can be made easier by storing the ContentType of the subclass in the Manufacturer instance . 通过将子类的ContentType存储在Manufacturer实例中,可以使此操作更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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