Question


I made a generic foreign key to be able to reference any type (A or B) of model in the Report model in a generic way.
It works fine but my problem is that now, I need to make a query to retrieve all Report instance referencing a specific type of Model (e.g. all Report with a foreign_key referencing class A). I tried to access the content_type in the database but apparently it is not possible (the variable does not exist...)
Here are my models:

class Report(models.Model):
  content_type = models.ForeignKey(ContentType)
  object_id = models.CharField(max_length=50)
  reported_item = generic.GenericForeignKey('content_type', 'object_id')

class A(models.Model):
  reports = generic.GenericRelation(Report)

class B(models.Model):
  reports = generic.GenericRelation(Report)

Do you have any idea how to do that?
Just in case it would change anything, I use mongoDB for my database.
Thanks very much!

EDIT:
When I display the report object in the db, here is the result:

db.website_report.findOne()
{
"_id" : ObjectId("50afa903a96c5c2f63000001"),
"content_type_id" : ObjectId("50afa903a96c5c2f63000000"),
"object_id" : "50afa8a8a96c5c2f53000001",
}

As you can see, the content of the database has nothing similar with my models so I don't know how to do a query to get all the report having a foreign_key of A.
Can you help me?

Was it helpful?

Solution

I don't understand why you think the db does not reflect your model. There you have the content type reference, and the object id. All you need to vdo is find out what content type refers to your model A, which is explained in the contenttype documentation:

ct = ContentType.objects.get_for_model(A)
objs = Report.objects.filter(content_type=ct)

OTHER TIPS

this is an example class from one of my projects, it shows limiting by certain models and by app using Q objects

class ContainerItem(models.Model) :
    """Items for containers"""
    limit = models.Q(model="page") & (models.Q(app_label='events') | models.Q(app_label='press')) & ~models.Q(app_label='press', model='category')
    object_type = models.ForeignKey(ContentType, limit_choices_to=limit)
    object_id = models.IntegerField(db_index=True)
    object = generic.GenericForeignKey(
        ct_field = "object_type", 
        fk_field = "object_id"
    )

Filtering on GenericForeignKeys is not possible:

Due to the way GenericForeignKey is implemented, you cannot use such fields directly with filters (filter() and exclude(), for example) via the database API. Because a GenericForeignKey isn't a normal field object, these examples will not work:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top