1

I'm new to Django and I'm trying to get the item from the database. The problem is the item is saved as a list in Django. And item[i] is not helping either. Please help me figure it out how to get the data

in the shell, I have tried

for x in NewsItem.objects.all():
     print(x.tag)

this will print

['babi kutil', 'babi hutan', 'babi liar', 'hutan indonesia']
['ibu aniaya anak']
['pilkada serentak 2018', 'bandung', 'nurul arifin', 'pilwalkot bandung 2018']
['narkoba di surabaya', 'bnnp jatim']
['pilkada serentak 2018', 'banten']

But I want to get each item, not as a list.

The NewsItem Model.

class NewsItem(models.Model):
    breadcrumbs = models.CharField(max_length=150, null=True)
    penulis = models.CharField(max_length=100, null=True)
    judul = models.CharField(max_length=200, null=True)
    berita = models.TextField()
    tag = models.TextField(null=True)
    url = models.CharField(max_length=200, unique = True)
    website = models.CharField(max_length=50, null=True)
    date = models.DateTimeField()
    @property
    def to_dict(self):
        data = {
            'data': json.loads(self.url),
            'tanggal': self.tanggal
        }
        return data

    def __str__(self):
        return self.url
4
  • 1
    Can you show NewsItem model? Commented Jun 12, 2018 at 6:33
  • I have edited it Commented Jun 12, 2018 at 6:39
  • Why is the data saved like that in the first place? It looks like the tag field contains a string representation of a list, which is not a very useful format. Commented Jun 12, 2018 at 6:45
  • it's because i don't know how to save them. this data is automatically insert into the database using scrapy pipeline. and i don't know how to split it into two tables. Commented Jun 12, 2018 at 6:48

1 Answer 1

2

You can use 2 for loops to achieve this and as you have mentioned tag as TextField, so you need to split it on comma.

for x in NewsItem.objects.all():
     tag_text = x.tag[1:-1]
     tag_list = tag_text.split(",")
     for tag in tag_list:
         print(tag)
Sign up to request clarification or add additional context in comments.

4 Comments

somehow they print each character so you get b,a,b,i, ,k,u,t,i,l not as a whole babi kutil
@ViraXeva, see the updated answer, as it is text field you need to split on comma.
it's work! but they seems to still have the bracket [ ] in the end. how to remove them?
@ViraXeva. check the updated answer. Now it will not contain brackets.

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.