How to make entry.category to be instance of CategoryProxy? See code for details:
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 # !!! I want CategoryProxy instance here
Cast from Category to CategoryProxy is ok too, but I am not very familiar with ORM internals to properly copy internal state...
EDIT. Reason: I added method to CategoryProxy and want to use him:
EntryProxy.objects.get(pk=1).category.method_at_category_proxy()
EDIT 2. Currently I implemented it like this:
EntryProxy._meta.get_field_by_name('category')[0].rel.to = CategoryProxy
but it looks terrible...
Adapting Bernd Petersohn's answer slightly, we then have:
This ought to be more economical with the database. For added improvements you could set a private attribute (
self._category
) the first time the method is called, then return that all subsequent times.This is an open Django issue: #10961 (Allow users to override forward and reverse relationships on proxy models with ForeignKey fields)
You can work around it by resetting the fields in question after you define the proxy models:
This question already has an accepted answer, but wanted to post this for anyone who may come searching.
You can patch the model at runtime with the new field so that relations work as expected. A full example can be seen here - https://gist.github.com/carymrobbins/8721082
Joseph Spiros's answer to one of my questions might help you:
Django Inheritance and Permalinks
I'm not sure how it'll work with proxy models.
To switch from a model class to a proxy class without hitting the database:
edit: the snippet above seems not working on django 1.4.
Since django 1.4, I take all value fields manually like this:
To switch from a queryset to a child proxy class without hitting database:
None of the current solutions (including the accepted one) work with Django 2.0.
Building on Matt Schinckel's work on overriding proxy model relations, here's a solution that will work with Django 2.0 and 2.1.