Dan
Dan

Reputation: 359

How to get data from django Model

Ok so I have this Model in django:

class Training(models.Model):
      url = models.URLField(max_length=100)
      title = models.CharField(max_length=100)
      topic = models.CharField(max_length=100)
      grouping = models.CharField(max_length=100)
      month = models.CharField(max_length=100)
      overallOrder = models.CharField(max_length=100)
      emailSent = models.CharField(max_length=100)

but how do I get the data from those fields?

If I drop to the sqlite shell this is what I get:

In [1]: from myapp.models import Training

In [2]: queryset = Training.objects.all()

In [3]: print (queryset)
<QuerySet [<Training: Training object>]>

But I want to be able to look at all the data in that database. I'm not sure how to do that.

Any help is appreciated. Thank you.

Upvotes: 0

Views: 4892

Answers (2)

Davy
Davy

Reputation: 1786

Django is "lazy" (see When is a Django QuerySet evaluated?)

This can be bypassed by forcing a query to be executed e.g. by requesting the nbr of elements, in your example execute:

queryset.len()

Upvotes: 1

Wariored
Wariored

Reputation: 1343

Add the str function:

class Training(models.Model):
      url = models.URLField(max_length=100)
      title = models.CharField(max_length=100)
      topic = models.CharField(max_length=100)
      grouping = models.CharField(max_length=100)
      month = models.CharField(max_length=100)
      overallOrder = models.CharField(max_length=100)
      emailSent = models.CharField(max_length=100)
      def __str__(self):
          return "Training with url %s and title %s"%(self.url, self.title)

You can add more fields in the function

Upvotes: 0

Related Questions