开发者

django: how to extend an existing model

开发者 https://www.devze.com 2023-02-27 07:02 出处:网络
there are plenty of examples the tell you how to extend the user model BUT I cannot find a real, complete and documented example on how to extend an existing model without having to follow the \"user

there are plenty of examples the tell you how to extend the user model BUT I cannot find a real, complete and documented example on how to extend an existing model without having to follow the "user profile pattern" (and honestly I wonder why).

In short, my use case is the following: I need开发者_开发技巧 to extend django-lfs's product model.

In LFS is registered like this (in lfs.catalog.admin):

from django.contrib import admin

[...]
from lfs.catalog.models import Product
[...]
class ProductAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("name", )}
admin.site.register(Product, ProductAdmin)
[...]

I tried to register mine (that subclasses it) but I got:

django/contrib/admin/sites.py", line 78, in register raise AlreadyRegistered('The model %s is already registered' % model.name)

So, someone suggested me that I have to unregister that object and register mine.

I did it like this:

from lfs.catalog.models import Product
from lfs.catalog.admin import ProductAdmin

admin.site.unregister(Product)

from lfs_product_highlights.catalog.models import Product

admin.site.register(Product,ProductAdmin)

No errors this time BUT there's no change, my custom fields are nowhere to be seen.

Any hints?


The reason why it's difficult is because of the object-relational impedance mismatch (love that phrase). Objects and classes do not map perfectly onto relational databases: ORMs like Django's attempt to smooth out the edges, but there are some places where the differences are just too great. Inheritance is one of these: there is simply no way to make one table "inherit" from another, so it has to be simulated via Foreign Keys or the like.

Anyway, for your actual problem, I can't really see what's going on but one possible way to fix it would be to subclass ProductAdmin as well, and specifically set the model attribute to your subclassed model.

0

精彩评论

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