gpt4 book ai didi

Django 区分查询集中的子项

转载 作者:行者123 更新时间:2023-12-01 23:47:13 24 4
gpt4 key购买 nike

我有一个名为“ block ”的模型

class Block(models.Model):
zone = models.ForeignKey(Zone)
order = models.IntegerField()
weight = models.IntegerField()
block_type = models.CharField(max_length=32, blank=True)

class Meta:
ordering = ['order']

def __str__(self):
return "Block "+str(self.order)

Block 对象有继承自它的子对象。 ImageBlock、VideoBlock 等...我会随着项目的进行添加更多内容

# Children of Block Object
class TextBlock(Block):
content = models.TextField(blank=True)

class ImageBlock(Block):
content = models.ImageField(blank=True)

class VideoBlock(Block):
content = models.FileField(blank=True)

我需要根据 block 的顺序对 block 执行操作。比如,

呈现 TextBlock1渲染图像 block 1呈现 TextBlock2

我使用类似 Block.objects.all() 的方式查询所有这些对象,然后遍历它们。当我这样做时,我如何区分每个对象是我的哪些对象?

如:

blockset = Block.objects.all()
for block in blockset:
if (**some way of differentiating if it's a TextBlock**):
print("This is a text block!")

知道我该怎么做吗?

非常感谢!

最佳答案

您可以使用 Content Types如果您不知道要获取的类的名称,请在父模型上。例如:

(未测试)

from django.contrib.contenttypes.models import ContentType

class Block(models.Model):
zone = models.ForeignKey(Zone)
order = models.IntegerField()
weight = models.IntegerField()
block_type = models.ForeignKey(ContentType, editable=False)

def save(self, *args, **kwargs):
if not self.id:
self.block_type = self._block_type()
super(Block, self).save(*args, **kwargs)

def __block_type(self):
return ContentType.objects.get_for_model(type(self))

def cast(self):
return self.block_type.get_object_for_this_type(pk=self.pk)

class Meta:
abstract = True

另请注意抽象基类,这意味着不会在数据库中创建模型。抽象字段将添加到子类的那些字段中,即

class TextBlock(Block):
content = models.TextField(blank=True)

但是,您无法查询本例中的抽象基类。如果这是你想要做的,那么简单地在你的基类上添加一个查找。

 TEXT = 'TXT'
IMAGE = 'IMG'
VIDEO = 'VID'
BLOCK_CHOICES = (
(TEXT, 'Text Block'),
(IMAGE, 'Image Block'),
(VIDEO, 'Video Block'),
)

class Block(models.Model):
zone = models.ForeignKey(Zone)
order = models.IntegerField()
weight = models.IntegerField()
block_type = models.CharField(max_length=3, choices=BLOCK_CHOICES)

然后查询:Block.objects.filter(block_type='Text Block')

或者在你的例子中:

blockset = Block.objects.all()
for block in blockset:
if block.block_type == "Text Block":
print("This is a text block!")

关于Django 区分查询集中的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com