Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Can I use objects.filter() for generic foreignkey?

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,
    )

What I want to do is,

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

But it occured errors:

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 already has GenericRelation. What's wrong with it?

Or do I have to override ojbect manager?

like image 436
user3595632 Avatar asked Feb 04 '18 06:02

user3595632


1 Answers

You can filter with content_type and object_id, instead of 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)
like image 50
Akash Avatar answered Oct 15 '22 18:10

Akash