2017-04-20 80 views
0

在django中,當我試圖查看我的[Post.objects.all()]其結果Post:Post Object而不是Post: titleenter image description here模型對象是反射對象而不是標題

這裏是我的models.py

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() [<Post: Post object>, <Post: Post object>]

+3

您需要提供更多的co de,它不可能回答這個問題 – techarch

+0

看起來你想要覆蓋'__repr__'而不是'__str__':https://docs.python.org/3.5/library/functions.html#repr –

回答

0

嘗試創建一個海峽方法後你的模型如下:

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方法可能會爲你工作。

0

試試這個,如果你不使用print

def __repr__(self): 
    return self.post_title 

print將調用__str__,那裏的控制檯輸出將是__repr__

0

我不知道這是否是你的剪切和粘貼,但缺口是錯誤的代碼

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 
相關問題