use*_*632 5 python django foreign-keys generic-foreign-key
符号.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)
Run Code Online (Sandbox Code Playgroud)
每日价格.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,
)
Run Code Online (Sandbox Code Playgroud)
我想做的是,
symbol = StockSymbol.objects.first()
MyDailyPrice.objects.filter(content_object=symbol)
Run Code Online (Sandbox Code Playgroud)
但它发生了错误:
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.
Run Code Online (Sandbox Code Playgroud)
StockSymbol已经有了GenericRelation。它出什么问题了?
还是我必须覆盖ojbect manager?
小智 5
您可以使用content_type和进行过滤object_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)
Run Code Online (Sandbox Code Playgroud)