我在My Django模型中使用名为Memberno的ForeignKey。在成员类中输入数据后,它在“memberno”字段中显示为其他类中的“成员对象”。对于ForeignKey,我使用'raw_id_fields'作为解决方法,但对于普通字段甚至'filter_horizontal',每个memberno值都显示为“member object”。我希望值显示在成员类中,即1,2,......
from django.db import models
# Create your models here.
class Members(models.Model):
DESIGNATION_CHOICES=(
('ADM', 'Administrator'),
('OFF', 'Club Official'),
('MEM', 'Ordinary Member'),
)
memberno = models.AutoField(primary_key=True)
fname = models.CharField(max_length=15)
sname = models.CharField(max_length=15)
onames = models.CharField(max_length=30, blank=True)
email = models.EmailField()
phoneNumber = models.CharField(max_length=15)
regNo = models.CharField(max_length=15)
designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES)
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True)
course = models.CharField(max_length=30, blank=True, null=True)
def __unicode__(self):
return u'%s %s %s' % (self.fname, self.sname, self.memberno)
def get_absolute_url(self):
return '%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.id)
def get_download_url(self):
return '%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.name)
class Security(models.Model):
memberno = models.ForeignKey(Members, unique=True)
username = models.CharField(max_length=30, primary_key=True)
password = models.CharField(max_length=70)
def __unicode__(self):
return u'%s %s %s' % (self.username, self.password, self.memberno)
class Subscriptions(models.Model):
memberno = models.ForeignKey(Members)
receiptNo = models.CharField(max_length=30, primary_key=True)
type = models.CharField(max_length=50)
date = models.DateField()
amount = models.FloatField(max_length=99)
def __unicode__(self):
return u'%s %s %s' % (self.receiptno, self.type, self.memberno)
class events(models.Model):
eventName = models.CharField(max_length=25)
eventID = models.AutoField(primary_key=True)
details = models.TextField()
attendanceFee = models.FloatField(max_length=99)
date = models.DateField()
memberno = models.ManyToManyField(Members)
def __unicode__(self):
return u'%s %s %s' % (self.eventName, self.eventID, self.memberno)
答案 0 :(得分:4)
管理界面似乎使用__str__()
来确定模型的显示。在创建模型时,我总是定义__unicode__()
和__str__()
。例如:
class Activity(models.Model):
activity_code = models.ForeignKey(ActivityCode)
note = models.TextField(blank=True)
def __str__(self):
return "(%s) %s" % (self.activity_code.short, self.note)
def __unicode__(self):
return u'(%s) %s' % (self.activity_code.short, self.note)
<强>更新强>
您的def __unicode__(self)
似乎没有在代码中正确缩进。因此,它不是您班级的一部分,也没有被使用。缩进在Python中非常重要。
答案 1 :(得分:2)
我不确定我是否完全理解您的问题,但您是否为模型定义了unicode方法?