I have a link between ads and products and stores, and I want to sort them in the admin by store:
class Ad(models.Model):
products = models.ManyToManyField(Product, blank = True)
device = models.ForeignKey(Display, on_delete = models.CASCADE)
class Product(models.Model):
name = models.CharField("name", max_length = 128)
store = models.ForeignKey(Store, on_delete = models.CASCADE)
class Store(models.Model):
name = models.CharField("name", max_length = 128)
so each Ad can have 0, 1, 2, 3 ... products linked to it. Now I want to make the field "store" sortable in the Ads admin list, therefore I tried to overwrite the get_queryset
method of AdAdmin
but got stuck on the way:
class AdAdmin(admin.ModelAdmin):
list_display = ["get_store", ... ]
def get_queryset(self, request):
qs = super().get_queryset(request)
qs = qs.annotate(storename = ####)
return qs
@admin.display(ordering = "storename")
def get_store(self, obj):
try:
return obj.products.all().first().store.name
except AttributeError:
try:
return obj.device.store.name
except AttributeError:
return "NEW"
So I want to annoatate my queryset by storename
and I want to be able to sort by store.name
alphabetically on my Ad
list admin page. I already found out how to annotate empty stores:
qs = qs.annotate(storename = Case(When(products_pk__isnull = True, then = Value("NEW"), default = Value("old")))
But this only got me so far ... how would I assign the value store.name
to default
dynamically using my given logic?
Every Ad has a condition: It can only be linked to (many) products of the same store.