Python 是否具有等效的 toString(),我可以将 db.Model 元素转换为 String 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16768302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:36:29  来源:igfitidea点击:

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

pythongoogle-app-enginedjango-templates

提问by Amru E.

I'm writing a ToDo list app to help myself get started with Python. The app is running on GAE and I'm storing todo items in the Data Store. I want to display everyone's items to them, and them alone. The problem is that the app currently displays all items to all users, so I can see what you write, and you see what I write. I thought casting my todo.author object to a string and seeing if it matches the user's name would be a good start, but I can't figure out how to do that.

我正在编写一个待办事项列表应用程序来帮助自己开始使用 Python。该应用程序在 GAE 上运行,我将待办事项存储在数据存储中。我想向他们展示每个人的物品,并且单独展示给他们。问题是该应用程序当前向所有用户显示所有项目,因此我可以看到您写的内容,您也可以看到我写的内容。我认为将我的 todo.author 对象转换为字符串并查看它是否与用户名匹配将是一个好的开始,但我不知道如何做到这一点。

This is what I have in my main.py

这是我在 main.py 中的内容

... 
user = users.get_current_user()

if user:
    nickname = user.nickname()
    todos = Todo.all()
    template_values = {'nickname':nickname, 'todos':todos}
...

def post(self):

    todo = Todo()
    todo.author = users.get_current_user()
    todo.item = self.request.get("item")
    todo.completed = False

    todo.put()      
    self.redirect('/')

In my index.html I had this originally:

在我的 index.html 中,我最初有这个:

<input type="text" name="item" class="form-prop" placeholder="What needs to be done?" required/>
...
 <ul>
{% for todo in todos %}
  <input type="checkbox"> {{todo.item}} <hr />
{% endfor %}
</ul>

but I'd like to display items only to the user who created them. I thought of trying

但我只想向创建它们的用户显示项目。我想尝试

{% for todo in todos %}
    {% ifequal todo.author nickname %}
  <input type="checkbox"> {{todo.item}} <hr />
    {% endifequal %}
{% endfor %}

to no avail. The list turns up blank. I assumed it is because todo.author is not a string. Can I read the value out as a string, or can I cast the object to String?

无济于事。列表变成空白。我认为这是因为 todo.author 不是字符串。我可以将值作为字符串读出,还是可以将对象转换为字符串?

Thanks!

谢谢!

Edit: Here is my Todo class

编辑:这是我的 Todo 课程

class Todo(db.Model):
author = db.UserProperty()
item = db.StringProperty()
completed = db.BooleanProperty()
date = db.DateTimeProperty(auto_now_add=True)

Will changing my author to a StringProperty effect anything negatively? Maybe I can forgo casting altogether.

将我的作者更改为 StringProperty 会产生负面影响吗?也许我可以完全放弃铸造。

采纳答案by Jeff Lockhart

In python, the str()methodis similar to the toString()method in other languages. It is called passing the object to convert to a string as a parameter. Internally it calls the __str__()method of the parameter object to get its string representation.

在python中,该str()方法类似于toString()其他语言中的方法。这称为传递对象以转换为字符串作为参数。它在内部调用__str__()参数对象的方法来获取其字符串表示。

In this case, however, you are comparing a UserPropertyauthor from the database, which is of type users.Userwith the nickname string. You will want to compare the nicknameproperty of the author instead with todo.author.nicknamein your template.

但是,在这种情况下,您正在比较UserProperty数据库中的作者,该作者的类型users.User为昵称字符串。您需要将nickname作者的属性与todo.author.nickname模板中的属性进行比较。

回答by Tim Hoffman

str()is the equivalent.

str()是等价的。

However you should be filtering your query. At the moment your query is all()Todo's.

但是,您应该过滤您的查询。目前您的查询是all()Todo 的。

todos = Todo.all().filter('author = ', users.get_current_user().nickname()) 

or

或者

todos = Todo.all().filter('author = ', users.get_current_user())

depending on what you are defining author as in the Todo model. A StringPropertyor UserProperty.

取决于您在 Todo 模型中定义的作者。AStringPropertyUserProperty

Note nicknameis a method. You are passing the method and not the result in template values.

注意nickname是一种方法。您正在传递方法而不是模板值中的结果。

回答by Daniel Roseman

You should define the __unicode__method on your model, and the template will call it automatically when you reference the instance.

你应该__unicode__在你的模型上定义方法,当你引用实例时模板会自动调用它。

回答by sinhayash

In function post():

在函数 post() 中:

todo.author = users.get_current_user()

So, to get str(todo.author), you need str(users.get_current_user()). What is returned by get_current_user() function ?

因此,要获得 str(todo.author),您需要 str(users.get_current_user())。get_current_user() 函数返回什么?

If it is an object, check does it contain a str()" function?

如果它是一个对象,检查它是否包含一个str()" 函数?

I think the error lies there.

我认为错误就在那里。

回答by Amirouche Zeggagh

In Python we can use the __str__()method.

在 Python 中,我们可以使用该__str__()方法。

We can override it in our class like this:

我们可以像这样在我们的类中覆盖它:

class User: 

    firstName = ''
    lastName = ''
    ...

    def __str__(self):
        return self.firstName + " " + self.lastName

and when running

和跑步时

print(user)

it will call the function __str__(self)and print the firstName and lastName

它将调用该函数__str__(self)并打印 firstName 和 lastName