Python 模型对象是反射对象而不是标题
在django中,当我试图查看我的Python 模型对象是反射对象而不是标题,python,django,django-models,Python,Django,Django Models,在django中,当我试图查看我的[Post.objects.all()]结果Post:Post-Object而不是Post:title时。 这是我的模特 from django.db import models # Create your models here. class Post(models.Model): post_title=models.CharField(max_length=50,blank=False) post_content=models.Te
[Post.objects.all()]
结果Post:Post-Object
而不是Post:title
时。
这是我的模特
from django.db import models
# Create your models here.
class Post(models.Model):
post_title=models.CharField(max_length=50,blank=False)
post_content=models.TextField()
creation_date=models.DateTimeField(auto_now=False,auto_now_add=True)
lastDate_modified=models.DateTimeField(auto_now=True,auto_now_add=False)
def __str__(self):
return self.post_title
输出是>>>Post.objects.all()
[,]
尝试为您的帖子模型创建一个str方法,如下所示:
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
description = models.TextField()
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
重写str方法可能对您有效。如果您没有使用
打印
,请尝试此方法
def __repr__(self):
return self.post_title
print
将调用\uuuu str\uuuu
,其中as控制台输出将是\uuuu repr\uuuuu
我不知道是否是您剪切粘贴的,但代码中的缩进是错误的
class Post(models.Model):
post_title=models.CharField(max_length=50,blank=False)
post_content=models.TextField()
creation_date=models.DateTimeField(auto_now=False,auto_now_add=True)
lastDate_modified=models.DateTimeField(auto_now=True,auto_now_add=False)
def __str__(self):
return self.post_title
应该是:
class Post(models.Model):
post_title=models.CharField(max_length=50,blank=False)
post_content=models.TextField()
creation_date=models.DateTimeField(auto_now=False,auto_now_add=True)
lastDate_modified=models.DateTimeField(auto_now=True,auto_now_add=False)
def __str__(self):
return self.post_title
您需要提供更多的代码,回答这个问题是不可能的。看起来您想要覆盖
\uuu repr\uuu
而不是\uu str\uu
: