2

I am trying to print out to the console the actual content value (which is html) of the field 'htmlfile': 16543. (See below)

So far I am able to print out the whole row using .values() method

Here is what I am getting in my python shell:

>>>
>>> Htmlfiles.objects.values()[0]
{'id': 1, 'name': 'error.html', 'htmlfile': 16543}
>>>

I want to print out the content of 16543.. I have scanned through the Django QuerySet docs so many times and still cannot find the right method..

Here is my data model in models.py:

class Htmlfiles(models.Model):
    name = models.CharField(max_length=30, blank=True, null=True)
    htmlfile = models.TextField(blank=True, null=True)  

    class Meta:
        managed = False
        db_table = 'htmlfiles'

Any assistance would be greatly appreciated.

3
  • Please clarify what you mean by "I want to print out the content of 16543". Do you mean you want to print only the value of the htmlfile field? Also it would be clearer if you posted your model class. Commented Dec 14, 2017 at 11:13
  • Yes, the value inside the htmlfile field.. I have added the model above Commented Dec 14, 2017 at 11:17
  • You should probably use a JsonField rather than TextField, then you can use the Postgres-specific query extensions. Commented Dec 14, 2017 at 12:17

1 Answer 1

2

You can fetch only the htmlfield value with:

Htmlfiles.objects.values('htmlfile')

Which, for each row, will give you an dictionary like so:

{'htmlfile': 12345}

So to print all the htmlfile values something like this is what you need:

objects = Htmlfiles.objects.values('htmlfile')
for obj in objects:
    print(obj['htmlfile'])
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you that makes a lot more sense, however I just want one value not all of them. Something like this print(obj['htmlfile'])[0] ??
If you want only one value then you first need to filter the query to fetch only one object - e.g., Htmlfiles.objects.get(... some filter here...).values('htmlfile'). But you need to know which object you want first.
I tried this .. Htmlfiles.objects.get(htmlfile=16543).values('htmlfile') and got back this error: AttributeError: 'Htmlfiles' object has no attribute 'values'
I don't understand why you would want to do that... what is the point of fetch the value of a field if you just fetched the object based on that field value itself?
But if you do want to do it, then simply do : Htmlfiles.objects.get(htmlfile=16543).htmlfile
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.