Django proxy model and ForeignKey

前端 未结 6 2093
温柔的废话
温柔的废话 2020-12-05 01:28

How to make entry.category to be instance of CategoryProxy? See code for details:

class Category(models.Model): pass

class Entry(models.Model):
    category         


        
6条回答
  •  温柔的废话
    2020-12-05 01:30

    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

    from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor
    
    def override_model_field(model, field, field_name, column_name):
        """Force override a field in a Django Model.
        Usage: override_model_field(
            MyModel, models.ForeignKey(OtherModel), 'other', 'other_id')
        :type model: django.db.models.base.ModelBase
        :type field: django.db.models.fields.Field
        :type field_name: basestring
        :type column_name: basestring
        """
        field.name = field_name
        field.attname = column_name
        for i, f in enumerate(model._meta.fields):
            if f.name == field_name:
                model._meta.fields[i] = field
                break
        else:
            raise TypeError('Model {!r} does not have a field {!r}.'
                            .format(model, field_name))
        model.add_to_class(field_name,
                           ReverseSingleRelatedObjectDescriptor(field))
    

提交回复
热议问题