1

I have two classes:

class Order(models.Model):
    ...
    date = models.DateTimeField(blank=True, verbose_name=u'Date add',default=datetime.now)
    price = models.DecimalField(max_digits=7, decimal_places=2, verbose_name=u'Price', blank=True, null=True)
    ...

    def __unicode__(self):
        return "%s" % (self.date)

class OrderItem(models.Model):
     ...
     date = models.DateTimeField(blank=True, verbose_name=u'Date add',default=datetime.now)
     order = models.ForeignKey(Order, verbose_name=u'Order')
     itemname = models.CharField(max_length=255, verbose_name=u'Item name')
     quantity = models.PositiveIntegerField(default=1, verbose_name=u'Quantity')
     price = models.DecimalField(max_digits=7, decimal_places=2, verbose_name=u'Price')


 def __unicode__(self):
         return "%s" % (self.itemname)

And I want to display orders with orderitems in list:

class OrderAdmin(admin.ModelAdmin):
    list_display = ('price','<????>ORDERITEMS</????>')

How to do it?

Nips
  • 13,162
  • 23
  • 65
  • 103
  • 1
    oops, copy and paste error, try this instead http://stackoverflow.com/questions/163823/can-list-display-in-a-django-modeladmin-display-attributes-of-foreignkey-field – Jingo Feb 01 '12 at 10:16

2 Answers2

2

It is a bit hard to do with your setup. If you use a related_name in your OrderItem model such as

order = models.ForeignKey(Order, related_name='items')

You could use it as a reference from the order to items. But again you have a OneToMany relationship so order have many items. You could crate a property in order to get you something like number_of_items such as

@property
def number_of_items(self):
    return self.items.count()

and use that in the OrderAdmin such as

class OrderAdmin(admin.ModelAdmin):
    list_display = ('price','number_of_items')

It is much easier if you are trying to access Order from OrderItem ModelAdmin because that returns one object so you could do:

class OrderItemAdmin(admin.ModelAdmin):
    list_display = ('itemname',order__price')

note the use of double underscore between order and price.

Meitham
  • 9,178
  • 5
  • 34
  • 45
0

I write this function to Order model:

def get_items(self):
    text = ""
    for i in self.oitems.all():
        text = text + '<br />' + i.itemname
    return text
get_items.allow_tags = True

And I add related_name="oitems" to Order Key in OrderItem. And it works.

Nips
  • 13,162
  • 23
  • 65
  • 103