Home > Net >  Django list_select_related gives me this error
Django list_select_related gives me this error

Time:12-29

#store/admin.py

@admin.register(models.Product)
class ProductView(admin.ModelAdmin):
    list_display = ['title', 'unit_price', 'inventory_status', 'collection_title',]
    list_editable = ['unit_price']
    list_per_page = 10
    list_select_related = ['collection']

#store/models.py

class Collection(models.Model):
    title = models.CharField(max_length=255)
    featured_product = models.ForeignKey(
        'Product', on_delete=models.SET_NULL, null=True, related_name=' ')

    class Meta:
        ordering = ['title']
    '''
    def __str__(self) -> str:
        return self.title
    '''


class Product(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField()
    unit_price = models.DecimalField(max_digits=6, decimal_places=2)
    inventory = models.IntegerField()
    last_update = models.DateTimeField(auto_now=True)
    collection = models.ForeignKey(Collection, on_delete=models.PROTECT)
    promotions = models.ManyToManyField(Promotion)

#Error I got: SystemCheckError

PS - I know I can use 'collection' in list_display directly as it is already a field in my product model, but I want to preload a related field/table using list_select_related and use 'collection_title' in list_display. Please help. Thank You.

ERRORS: <class 'store.admin.ProductView'>: (admin.E108) The value of 'list_display[3]' refers to 'col lection_title', which is not a callable, an attribute of 'ProductView', or an attribute or method on 'store.Product'.

CodePudding user response:

I think you're wrong, as far as I know list_select_related is to reduce your query, but your error is something else, here it says "list_display [3]" referred to colection_title, which is not a attribute or callable method of model Product or ProductView class.

django validate this items(list_display) In the following link, you can see the validate function(_check_list_display): https://github.com/django/django/blob/950d697b95e66deb3155896e0b619859693bc8c6/django/contrib/admin/checks.py#L732

If you want to access the related field in other models, you can create a function in your ProductView link this:

class ProductView(admin.ModelAdmin):
    list_display = ['title', 'unit_price', 'inventory_status', 'collection_title',]
    list_editable = ['unit_price']
    list_per_page = 10
    list_select_related = ['collection']

    def  collection_title(self, obj):
         return obj.collection.title
  • Related