IMBlues / IMBlues.github.io

My legacy blog, moved to https://github.com/IMBlues/nobelium
2 stars 0 forks source link

django-orm-best-practice-II #10

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

Django ORM:天使与魔鬼 II

CRUD boy 回来了

https://emergencyexit.xyz/django-orm-best-practice-II.html

IMBlues commented 2 years ago

包含外键时需要谨慎使用 Django Proxy Model

Model 中包含外键时(ForeignKeyManyToManyFieldOneToOneField)使用 Proxy Model,会发现所有外键查询拿到的对象仍将指向原模型,而非 Proxy 模型,这会导致某些场景(例如使用了 django-filter)时会异常报错。

class Category(models.Model): pass

class Entry(models.Model):
    category = models.ForeignKey(Category)

class EntryProxy(Entry):
    class Meta:
        proxy = True

class CategoryProxy(Category):
    class Meta:
        proxy = True

entry = EntryProxy.objects.get(pk=1)
entry.category # not a CategoryProxy instance here !!!

目前还没有一个足够优雅的解决方案。

参考: