Home > Software design >  display objects from inline model in DetailView
display objects from inline model in DetailView

Time:04-26

I have 2 models Product and Resource. Resource has to be a TabularInline model in my admin panel. I am struggling with filtering resource titles that are related only to this product. Since it is a ForeignKey I should use select_related but I am not sure how to use it in my case. For now, the loop in my HTML file gives me all sales files (from all products).

models.py

class Product(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField('title', max_length=400, default='')
    slug = models.SlugField(unique=True, blank=True, max_length=600)

class Resource(models.Model):
    id = models.AutoField(primary_key=True)
    type = models.CharField(max_length=32, choices=RESOURCE_TYPE, default='sales')
    title = models.CharField(max_length=400, blank=False, null=False, default='')
    related_files = models.FileField(upload_to='recources/', null=True, blank=True) 
    publish = models.DateTimeField('Published on', default=timezone.now)
    resources = models.ForeignKey(Product, default='', on_delete=models.PROTECT, null=True, related_name='resources')

admin.py

class Resourceinline(admin.TabularInline):
    model = Resource
    
class ProductAdmin(ImportExportModelAdmin):
    inlines = [
        Resourceinline,
    ]
    resource_class = ProductResource

admin.site.register(Product, ProductAdmin)

views.py

class ProductDetailView(DetailView):
    template_name = 'ProductDetailView.html'
    model = Product

    def get_context_data(self, **kwargs):
            context = super(ProductDetailView, self).get_context_data(**kwargs)
            resources_sales = Resource.objects.select_related('resources').filter(resources_id =1, type='sales') # not sure what to put here
            context['resources_sales'] = resources_sales
            return context

ProductDetailView.html

{% for resource in resources_sales.all %}
    <p>{{resource.title}}</p>
{% endfor %}

Question

Where am I making the mistake and how can I display resource objects that are related to type=sales and are related only to this product in DetailView.

Edit

I realized that there is a column named resources_id that is connecting both models. Now I am struggling to filter it by id of current DetailView. I put resources_id=1 in my views.py but it must relate to DetailView that user is currently looking at. I tied to put resources_id=self.kwargs['id'] but it gives me KeyError at /product/test-product/ 'id' How can I do that?

CodePudding user response:

since you are using generic DetailView you can refer to the current object with self.get_object(). actually that return the single object that view display. however you can use instateself.object too.

so you can filter the Product related Resources using Resource.objects.filter(resources=self.get_object(), type='sales')

you can read more Single object mixins

  • Related