areski / django-nvd3

Django wrapper for nvd3 - It's time for beautiful charts
Other
416 stars 124 forks source link

Use data from list of model objects #40

Closed ttuti closed 9 years ago

ttuti commented 9 years ago

I have a model Iris with data about flowers (commonly used in R). I'm trying to get the xdata attribute and the ydata attribute for pieChart but it keeps failing. My code looks like the following: The model

class Iris(models.Model):
   species = models.CharField(max_length=100)
   sepal_length = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)
   sepal_width = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)
   petal_length = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)
   petal_width = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)

      def as_json(self):
       return dict(
                species = self.species,
                sepal_width =self.sepal_width,
                sepal_length= self.sepal_length,
                petal_width=self.petal_width,
                petal_length=self.petal_length) 

The view

  def index(request):
      irisData = [iris.as_json() for iris in Iris.objects.all()]
      irisJson = simplejson.dumps(irisData)

My problem is that, every time I try to initialize the pieChart xdata attribute, I get the error:

     Django Version:    1.6.5
     Exception Type:    TypeError
     Exception Value:   string indices must be integers, not str

The troublesome line is

         xdata=irisJson['species']

How exactly should I supply the xdata values from Iris json array using attribute name?

The irisJson json data looks like this:

[{"sepal_width": 3.50, "petal_width": 0.20, "species": "setosa", "sepal_length": 5.10, "petal_length": 1.40}, {"sepal_width": 3.00, "petal_width": 0.20, "species": "setosa", "sepal_length": 4.90, "petal_length": 1.40}, {"sepal_width": 3.20, "petal_width": 0.20, "species": "setosa", "sepal_length": 4.70, "petal_length": 1.30}, {"sepal_width": 3.10, "petal_width": 0.20, "species": "setosa", "sepal_length": 4.60, "petal_length": 1.50}, {"sepal_width": 3.60, "petal_width": 0.20, "species": "setosa", "sepal_length": 5.00, "petal_length": 1.40}, {"sepal_width": 3.90, "petal_width": 0.40, "species": "setosa", "sepal_length": 5.40, "petal_length": 1.70}]

areski commented 9 years ago

Xdata is list of key-lables that will be represented on the piechart. You should look at the piechart example that is provided: https://github.com/areski/django-nvd3/blob/develop/demoproject/demoproject/views.py#L20