Django 1.7:我可以使用prefetch\u related()来获取没有相关\u名称的ForeignKey吗?

2024-10-01 09:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将项目显示到一个数据库点击量尽可能少的页面(有很多项目)。假设我的模型是这样的:

Class Item(models.Model):
    name = models.CharField(max_length=50, unique=True)

Class ItemAttribute(models.Model):
    item = models.ForeignKey(Item)
    name = models.ForeignKey(ItemAttributeName)

Class ItemAttributeName(models.Model):
    name = models.CharField(max_length=50, unique=True)

请注意,没有相关名称。项目有一个属性列表,一个好的相关名称我可以使用将是项目属性。但对于这个问题,我不会那么做。我想知道是否有一种方法可以查询项目及其属性的列表,这样我就可以确定该项目是已使用的还是新的。你知道吗

Item.ItemAttribute.ItemAttributeName.name = "USED"

看起来像

Item.item_attributes[0].name.name = "USED"

诸如此类的事情,你就明白要点了。你知道吗

是否可以查询prefetch\u related()使用的属性名称?我的意思是我知道这个名字和你有关,所以这个问题看起来很愚蠢,但我想知道这是否可能。显而易见的答案是不要再做傻子了,加上一个相关的名字,但现在不用担心。你知道吗


Tags: 项目name名称truemodel属性modelsitem
2条回答

不需要定义相关的名称(除非有冲突)。Django定义了一个非常好的默认值。你知道吗

但是,您的模型结构还有更深层次的问题。ItemAttribute只是多对多关系中的直通表。您根本不需要它,因为Django会自动定义它。只需声明您关心的实际关系,即Item和Attribute之间的关系:

class Item(models.Model):
    name = models.CharField(max_length=50, unique=True)
    attributes = models.ManyToManyField('ItemAttributeName')

现在您可以直接使用prefetch_related获取所有内容:

items = Item.objects.all().prefetch_related('attributes')

一种可能的解决方案是检索ItemAttributes的查询,以便

attributes = ItemAttribute.objects.filter(item=<given_item>)

然后看看这些属性的名称。。。你知道吗

for attribute in attributes:
    if attribute.name.name == "USED":
        # do something
    else:
        # do something else

但是这个解决方案不使用预回迁相关的,因为它意味着你已经查询过的项目列表中的给定项目。。。你知道吗

items = Item.objects.filter(<some_filter>)
for item in items:
    check_if_used(item)

相关问题 更多 >