Reputation: 1154
I have this object in my django model :
class Stock(models.Model):
name = models.CharField(null=True,blank=True,max_length=20)
def ___str__(self):
return self.name
def __unicode__(self):
return self.name
When I see it in the django admin it works well.
But in the admin when I want to see this object :
class StockData(models.Model):
stock = models.ForeignKey(Stock,on_delete=models.PROTECT,null=True,blank=True)
date = models.DateTimeField(null=True,blank=True)
interval = models.CharField(null=True, blank=True,max_length=2)
def ___str__(self):
return self.stock+ ":" + str(self.date)
def __unicode__(self):
return self.stock + ":" + str(self.date)
with this admin :
from django.contrib import admin
from .models import StockData
# Register your models here.
class StockData_Admin(admin.ModelAdmin):
list_display = (
'date',
'stock',
'interval'
)
admin.site.register(StockData,StockData_Admin)
but in the admin page the stock object is represented as :
Stock object (1)
edit :
So how to solve this ?
My django version :
>>> import django
>>> django.VERSION
(2, 0, 0, 'final', 0)
Thanks and regards
Upvotes: 1
Views: 1501
Reputation: 312
There's a typo in your Stock
definition - Python's magic methods start and end with double underscore, Stock
's str currently starts with three underscores instead of two. When the Stock
instance is printed, it falls back to the models.Model
default str implementation. Once the suprefluous underscore is removed, you will see the Stock
displayed correctly:
Upvotes: 7
Reputation: 2439
In models.py try something like this (not tested)
class Stock(models.Model):
name = models.CharField(blank=True,max_length=20)
# charfield default value is empty string so null true not needed
def __str__(self):
title = 'Empty title'
if self.name != '':
title = self.name
return title
def __unicode__(self):
title = 'Empty title'
if self.name != '':
title = self.name
return title
class StockData(models.Model):
stock = models.ForeignKey(Stock,on_delete=models.PROTECT,null=True,blank=True)
date = models.DateTimeField(null=True,blank=True)
interval = models.CharField(blank=True,max_length=2)
def __str__(self):
title = 'Empty title'
if(all([self.stock, self.date])):
title = '{}:{}'.format(self.stock, self.date)
return title
def __unicode__(self):
title = ''
if self.stock and self.date:
title = self.stock + ':' + self.date
return title
in admin.py try this
class StockData_Admin(admin.ModelAdmin):
list_display = (
'get_date',
'get_stock',
'get_interval'
)
def get_date(self, obj):
return obj.date
def get_stock(self, obj):
return obj.stock
def get_interval(self, obj):
return obj.interval
get_date.empty_value_display = 'No available date'
get_stock.empty_value_display = 'No available stock'
get_interval.empty_value_display = 'No available interval'
admin.site.register(StockData,StockData_Admin)
Upvotes: 0