Django中的泛型

Django中的泛型,django,generics,django-models,django-contenttypes,Django,Generics,Django Models,Django Contenttypes,有人能把这个带有泛型的Java伪代码翻译成Django模型吗?我不理解内容类型的概念。也可以省略映射,只列出KeyValuePairs或KeyValueExamples class Dictionary<T extends KeyValuePair> class KeyValuePair String key String value class KeyValueExample extends KeyValuePair String example cl

有人能把这个带有泛型的Java伪代码翻译成Django模型吗?我不理解内容类型的概念。也可以省略映射,只列出KeyValuePairs或KeyValueExamples

class Dictionary<T extends KeyValuePair>

class KeyValuePair
    String key
    String value

class KeyValueExample extends KeyValuePair
    String example

class Container
    Dictionary<KeyValuePair> itemsOne
    Dictionary<KeyValueExample> itemsTwo
类字典
类KeyValuePair
串键
字符串值
类KeyValueExample扩展了KeyValuePair
字符串示例
类容器
字典项目
字典项two

Django的
contenttypes
与Java中的泛型没有任何共同之处。Python有一个动态类型系统,因此不需要泛型

这意味着您可以将任何类的任何对象放入字典:

class Container(object):

    def __init__(self):
        self.itemsOne = {}
        self.itemsTwo = {}

container = Container()
container.itemsOne['123'] = '123'
container.itemsOne[321] = 321
container.itemsTwo[(1,2,3)] = "tuple can be a key"
如果您想在django模型中实现您的类,那么代码可以是这样的:

class KeyValuePairBase(models.Model):    
    key = models.CharField(max_length=30)
    value = models.CharField(max_length=30)    
    class Meta:
        abstract = True    

class KeyValuePair(KeyValuePairBase):
    pass    

class KeyValueExample(KeyValuePairBase):
    example = models.CharField(max_length=30)    

class Container(models.Model):    
    items_one = models.ManyToManyField(KeyValuePair)
    items_two = models.ManyToManyField(KeyValueExample)

# usage of these models

kvp = KeyValuePair.objects.create(key='key', value='value')
kve = KeyValueExample.objects.create(key='key', value='value',
                                     example='Example text')

container = Container.objects.create()
container.items_one.add(kvp)
container.items_two.add(kve)

Django的模型表示数据库表,而不是任意对象。你到底想在这里做什么?关于我添加到帖子中的列表的想法呢?我想使用django.db模型