开发者

Using contentType for raw_id_fields

In my application, i have a model definition like:

class SomeModel(models.Model):
    someFK = Models.ForeignKey(SomeModel, null=True, blank=True)
    otherFK = Models.ForeignKey(OtherModel, null=True开发者_运维知识库, blank=True)
    ...

This model keep data about Logs, and there are more than 1 kind of model to be logged, so i place a FK for each related Model. For each record, only one of the FK's is used, other FK's set NULL = True.

But i do not wish to alter my model when i need to log some other thing. So i alter my model so:

class SomeModel(models.Model):
    content_type = models.ForeignKey(ContentType)
    content_id = models.IntegerField()

So i used following to get what i want:

content_type.get_object_for_this_type(id=content_id)

Its ok. But when admin.py comes into play, it causes problem, because i have 1.000.000+ data for some related models to be logged, so i need to use raw_id_fields. Since i do not have FK for each related model, i must use ContentType model and content_id, but i do not know how to do that using ContentType?


Django grappelli extends Django admin functionality in generic lookup. So your ModelAdmin could have something like:

class SomeModelAdmin(ModelAdmin):
    related_lookup_fields = {
        'generic': [['content_type', 'object_id'], ],
    }

Using contentType for raw_id_fields

It solves my lookup problem. I hope this solve your problem too.


I know this doesn't answer your question exactly, but you should be using generic relations instead of multiple foreignkeys. Then you can achieve the end-goal of what you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜