Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin list_display foreign key id without join

class CDR(models.Model):
    order = models.ForeignKey(Order)
    call = models.ForeignKey(Call)
    start_date = models.DateTimeField(auto_now_add=True)
    end_date = models.DateTimeField(null=True)
    remark = models.CharField(max_length=200, null=True)

class CDRAdmin(admin.ModelAdmin):
    search_fields = ('order__id',)
    raw_id_fields = ('call', 'order')
    list_display = ('call', 'order', 'start_date', 'remark')

    models = CDR

since there are 2 foreign keys in CDR table Call and Order but to show these ids in the list_display it makes join with Call and Order tables and it results to slow queries since all these 3 tables have huge data rows.

Is there a way to solve it without join ?

As I used call__id and order__id in list_display it raises ImproperlyConfigured and without __id it display __repr__ object on joing results.

like image 719
PiyusG Avatar asked Jan 24 '26 03:01

PiyusG


1 Answers

Foreign key's id is available as <name>_id attribute so you can show ids via custom method:

class CDRAdmin(admin.ModelAdmin):

    list_display = ('call_id_display', 'order_id_display', 'start_date', 'remark')

    def call_id_display(self, obj):
       return obj.call_id
    call_id_display.short_description = 'Call ID'

    def order_id_display(self, obj):
       return obj.order_id
    order_id_display.short_description = 'Order ID'
like image 97
catavaran Avatar answered Jan 25 '26 20:01

catavaran