gpt4 book ai didi

具有同一模型的多个内联的 Django 管理

转载 作者:行者123 更新时间:2023-12-05 03:15:48 27 4
gpt4 key购买 nike

我在管理界面中遇到 StackedInlines 前缀的问题。我会尝试发布所有必要的代码。

models.py(简要)

##### Base classes

class BaseItem(models.Model):
pass

class BaseProvider(PolymorphicModel):
items = models.ManyToManyField(BaseItem, through="ItemProvided")

class ItemProvided(models.Model):
item = models.ForeignKey(BaseItem)
provider = models.ForeignKey(BaseProvider)
price = models.IntegerField()

##### Implementing ones

class Hotel(BaseProvider):
pass

class Room(BaseItem):
pass

class Service(BaseItem):
pass

这个层次结构如下:酒店是可以提供房间或服务的提供者。

admin.py(简要)

#### Creating admin.StackedInline for Rooms

class RoomInlineFormSet(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
kwargs.update({'prefix':'room'})
super(RoomInlineFormSet, self).__init__(*args, **kwargs)

class HotelRoomInline(admin.StackedInline):
# This class also filters 'item' choiceField in order to have only ItemProvideds which are rooms
model = ItemProvided
formset = RoomInlineFormSet


#### Creating admin.StackedInline for Services

class ServiceInlineFormSet(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
kwargs.update({'prefix':'service'})
super(ServiceInlineFormSet, self).__init__(*args, **kwargs)

class HotelServiceInline(admin.StackedInline):
# This class also filters 'item' choiceField in order to have only ItemProvideds which are services
model = ItemProvided
formset = ServiceInlineFormSet


#### Adding inlines to HotelAdmin and model to admin interface

class HotelAdmin(admin.ModelAdmin):
inlines = [
HotelRoomInline,
HotelServiceInline,
]

admin.site.register(Hotel, HotelAdmin)

通过这段代码,我设法在酒店模型的管理界面中获得了两个独立的 StackedInline,每个 StackedInline 都允许仅选择 itemprovided 的适当子集。太好了。

问题:如果创建了一个 itemprovided,例如在房间的 StackedInline 中;两个 StackedInlines 都填充了数据...前缀管理不善...

  • 我没有看到代码中有什么明显的错误吗?
  • 是否有其他好的选择二在管理界面中获取伪装的布局?

最佳答案

比使用自定义查询集内联更好的解决方案是使用 Proxy Modelscustom manager它添加了默认过滤。使用该解决方案,您可以轻松地在管理员之外重新使用这些模型:

# models.py

class HotelRoomManager(models.Manager):
def get_query_set(self):
return super(HotelRoomManager, self).get_query_set().filter(prefix='room')

class HotelRoom(ItemProvided):
""" Only ItemProvided with prefix=room """
objects = HotelRoomManager()

class Meta:
proxy = True

class HotelServiceManager(models.Manager):
def get_query_set(self):
return super(HotelServiceManager, self).get_query_set().filter(prefix='service')

class HotelService(ItemProvided):
""" Only ItemProvided with prefix=service"""
objects = HotelServiceManager()

class Meta:
proxy = True


#### admin.py

class HotelRoomInline(admin.StackedInline):
model = HotelRoom

class HotelServiceInline(admin.StackedInline):
model = HotelService

class HotelAdmin(admin.ModelAdmin):
inlines = [
HotelRoomInline,
HotelServiceInline,
]

关于具有同一模型的多个内联的 Django 管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9738995/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com