Nadun Perera
Nadun Perera

Reputation: 655

DetailView with data from two other Models

I would like to get some advice from the community.

I have recenlty started learning Django and have a question regarding the structure of the application.

I have a URL http://127.0.0.1:8000/asset/2/, a DetailView for my Asset model which also has two card blocks that houses data for two other models Tenant and Service. Check the screenshot below.

enter image description here

I am generating the above view from the asset/views.py file. Code as below.

class AssetMultipleDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView):
    model = Asset
    context_object_name = 'asset'
    template_name = 'asset/asset_multiple_detail.html'

    def test_func(self):
        asset_multiple = self.get_object()
        if self.request.user == asset_multiple.owner:
            return True
        return False

    def get_context_data(self, **kwargs):
        context = super(AssetMultipleDetailView, self).get_context_data(**kwargs)
        context['tenants'] = Tenant.objects.filter(asset=context['asset']).order_by('created')
        context['services'] = Service.objects.filter(asset=context['asset']).order_by('created')
        return context

When you click on the Add New Tenant button, I use the below URL in tenant/urls.py

path('new/asset/<int:pk>/', TenantAssetCreateView.as_view(), name='tenant_asset_create'),

This URL generates a CreateView for Tenant. I use the primary key of the asset in the URL to load up only the right asset to the Asset selection field. Please see the image below.

enter image description here

Everything works well.

I would like to know whether is this the best way to achieve this? Will this be easily maintainable as there are more views similar to this upcoming in the application.

Any advice is much appreciated. Thank you in advance.

Upvotes: 0

Views: 162

Answers (1)

NKay
NKay

Reputation: 140

I am not quite sure what your models look like. Does tenant have a manytomany relation to asset (a tenant can be related to any amount of assets)? Or does tenant have a foreign key to asset in your design (a tenant has exactly one related asset)? Based on the screenshot I assume the latter.
Or do you want an asset to only have one tenant (foreign key on asset to tenant)?

Loading the correct asset from the URL is perfectly valid. You should maybe make asset in the form disabled, so it can not be manipulated.

In the CreateView you could override form_valid(self,form) to set self.object.asset to the one you need.

Upvotes: 1

Related Questions