开发者

displaylist of children in parent model one-to-many

I am learning django admin, i have to models with a one-to-many relation between them. I got something like Manufacturer model where i can add different car manufacturers, and Car model for adding cars. In my django admin page i want to be able to display_list of all cars manfuctred by say manufacturer1 when i click on manufacturer1 entry.

I have found a trick by using Inline model in manufacturer admin model, the problem is that it loads every entry in the database and it takes some time as it's a开发者_开发知识库 big table.

Is there any method else to do that or do i have to create a new template ?

EDIT: The goal is not to load every Car that is FK to Manufacturer1 like with InlineModelAdmin but to get the same display as with display_list with results split in pages


Answer for your updated question:

the way to do it could be by using ProxyModels and overriding ModelAdmin.queryset

You extend the Car model via FordCar, GMCar and use proxy=True in the Meta class, for both those.

Then you can register seperate admins for each of FordCar and GMCar and override the queryset method in each of those ModelAdmin to filter for the respective manufacturer.

Ex:

class FordCarAdmin(admin.ModelAdmin)
    list_display = fields = ['name','model','engine']

    def queryset(self,request):
        qs = super(MyModelAdmin, self).queryset(request)
        return qs.filter(manufacturer__name='Ford')

admin.site.register(FordCar,FordCarAdmin)


You have two options.

The easiest approach is to look at the relationship in reverse. Instead of going to a manufacturer change form and seeing all their cars. Go to the cars changelist and filter by manufacturer. You'll have to set the list_filter attribute on the car ModelAdmin to include manufacturer.

Option two, is going to be a huge pain, but you can override change_view on the manufacturer ModelAdmin to add the list of that manufacturer's cars to extra_context. Then, you'll have to override the admin template at 'templates/admin/yourapp/manufacturer/change_form.html'. You can then add to that template to produce the kind of list you're looking for using the list of cars you passed into extra_context, drawing on 'django/contrib/admin/templates/change_list.html' for inspiration.

Give the Django docs on the Admin a good thorough read. There's actually a wealth of info in there.


You don't need any hack. Django admin displays only Cars that have a FK to Manufacturer1, when you select Manufacturer1, as long as you have used the InlineModelAdmin right and as intended.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜