开发者

Django: How to get string from CharField object?

开发者 https://www.devze.com 2023-01-07 19:53 出处:网络
I have a Django model, which is essentially a list of words. It is very simple and is defined as follows:

I have a Django model, which is essentially a list of words. It is very simple and is defined as follows:

class Word(models.Model):
    word = models.CharField(max_length=100)

I need the particular word as a string object. (开发者_开发知识库I am replacing all the characters in the word with asterisks for a simple Hangman game.) However, I cannot seem to get the word as a string object.

I tried adding this method to the Word class, but that did not seem to work either.

def __str__(self):
    return str(self.word)

I get an empty string object instead of the word.

What do I need to do to get the value of the CharField as a string object? Thanks for your help.

Edit: The weird thing for me is that it has no problem returning an integer. For example, if I were do do something like this:

word = Word(pk=2821)
print word.id

... it would print 2821, the id of that particular record.


Are you sure you're fetching the Word objects correctly? The line in your example word = Word(pk=2821) creates a new Word object with a pk of 2821 and a blank word field. If you've fetched an actual Word object from the database that has a value in its word field, then word.word should return a string. E.g.

>>>> w1 = Word(pk=5, word='eggs')
>>>> w1.word
'eggs'
>>>> w1.save()
>>>> w2 = Word.objects.get(pk=5)
>>>> w2.word
u'eggs'

Can you also verify that the words are being correctly stored in your database by connecting to it with a DB client and looking at the output of:

SELECT word FROM yourappname_word LIMIT 20;

Like I said, word.word should work, so the problem might lie in how you're saving or fetching your Word objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消