【问题标题】:Django: Can I use objects.filter() for generic foreignkey?Django:我可以使用 objects.filter() 作为通用外键吗?
【发布时间】:2018-07-14 07:20:00
【问题描述】:

symbol.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

【问题讨论】:

    标签: python django foreign-keys generic-foreign-key


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-28
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      相关资源
      最近更新 更多