我的用户模型如下。
**model.py**
class User(models.Model):
#user_idx = models.AutoField('user-num', primary_key=True)
user_idx = models.OneToOneField(Counsel, primary_key=True, db_column="user_idx", related_name="useridx" , on_delete="models.DO_NOTHING")
district_id = models.IntegerField(blank=True, null=True)
user_email = models.CharField(unique=True, max_length=200)
user_password = models.CharField(max_length=200)
user_name = models.CharField(max_length=100)
class Meta:
managed = False
db_table = 'user'
verbose_name_plural = "USER"
class Counsel(models.Model):
counsel_idx = models.AutoField(primary_key=True)
category_sub_idx = models.IntegerField(blank=True, null=True)
user_idx = models.IntegerField()
counsel_title = models.CharField(max_length=255)
counsel_contents = models.TextField()
counsel_status = models.CharField(max_length=1, choices=COUNSEL_STATUS)
answer_count = models.IntegerField()
hit = models.IntegerField()
user_ip = models.CharField(max_length=20, blank=True, null=True)
register_date = models.DateTimeField()
update_date = models.DateTimeField()
deleted = models.CharField(max_length=1, choices=DELETE_STATUS)
然后django管理员创建了源代码,如下所示:
class UserAdmin(admin.ModelAdmin):
list_display = ('user_idx', 'show_firm_url', 'user_name',)
def show_firm_url(self, obj):
return format_html("<a href='/admin/user/view/{0}'>{1}</a>", obj.user_idx, obj.user_email)
show_firm_url.short_description = 'E-mail'
律师对象(1494) 请告诉我如何获取此号码。 律师对象(1494)-----> 1494
答案 0 :(得分:0)
Django在需要将模型实例表示为字符串时,会使用在模型实例上定义的__str__()
方法:
class User(models.Model):
# ... your fields
def __str__(self):
return "%d" % self.user_idx.pk
__unicode__()
仅在您未在Python3上运行Django的情况下有效。
答案 1 :(得分:-1)
覆盖 =>此方法适用于python2而非python3 __unicode__
可以更改Django为模型对象渲染的内容
覆盖__str__
可以更改Django为模型对象渲染的内容
class User(models.Model):
user_idx = models.OneToOneField(Counsel, primary_key=True,
db_column="user_idx", related_name="useridx" , on_delete="models.DO_NOTHING")
district_id = models.IntegerField(blank=True, null=True)
user_email = models.CharField(unique=True, max_length=200)
user_password = models.CharField(max_length=200)
user_name = models.CharField(max_length=100)
def __str__(self):
return "%d" % self.user_idx.id # id is field of Counsel object you want to show
如果您要更改Counsel
对象表示的内容,则必须将该模型更改为此模型:
class Counsel(models.Model):
counsel_idx = models.AutoField(primary_key=True)
category_sub_idx = models.IntegerField(blank=True, null=True)
user_idx = models.IntegerField()
counsel_title = models.CharField(max_length=255)
counsel_contents = models.TextField()
counsel_status = models.CharField(max_length=1, choices=COUNSEL_STATUS)
answer_count = models.IntegerField()
hit = models.IntegerField()
user_ip = models.CharField(max_length=20, blank=True, null=True)
register_date = models.DateTimeField()
update_date = models.DateTimeField()
deleted = models.CharField(max_length=1, choices=DELETE_STATUS)
def __str__(self):
return "%d" % self.user_idx