gpt4 book ai didi

python - Django:我可以将 objects.filter() 用于通用外键吗?

转载 作者:行者123 更新时间:2023-11-28 17:09:37 25 4
gpt4 key购买 nike

符号.py

class Symbol(BaseModel):
name = models.CharField(max_length=30,)

class Meta:
abstract = True

class StockSymbol(Symbol):
market = models.CharField(max_length=10,)
my_daily_price = GenericRelation(MyDailyPrice)

daily_price.py

class DailyPrice(BaseModel):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')

class Meta:
abstract = True

class MyDailyPrice(DailyPrice):
open = models.DecimalField(
max_digits=15,
decimal_places=2,
)

我想做的是,

symbol = StockSymbol.objects.first()
MyDailyPrice.objects.filter(content_object=symbol)

但是出现错误:

FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation.

StockSymbol 已经有 GenericRelation。有什么问题吗?

或者我是否必须覆盖 ojbect manager

最佳答案

您可以使用 content_typeobject_id 来过滤,而不是 content_object

from django.contrib.admin.options import get_content_type_for_model
symbol = StockSymbol.objects.first()
MyDailyPrice.objects.filter(content_type=get_content_type_for_model(symbol), object_id=symbol.pk)

关于python - Django:我可以将 objects.filter() 用于通用外键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48605567/

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