1

I would simply like to transform a prefetch_related query into a Panda dataframe with all the information from the two models below. This should be very simple but somehow nothing works. I get a 'Capture_set is not defined' with the code below. Any idea ?

class Capture(models.Model):
  species_name = models.CharField(max_length=50)
  total_capture = models.IntegerField()



class Species(models.Model):
  species_name = models.ForeignKey(Capture, on_delete=models.DO_NOTHING)
  length = models.IntegerField()
  weight = models.IntegerField()


data = pd.DataFrame(list(Species.objects.all().prefetch_related(Capture_set)))
Blue
  • 179
  • 1
  • 10
  • It should read dataframe, not database. sorry. – Blue May 13 '19 at 15:27
  • `Capture_set is not defined` sounds like you haven't defined a variable `Capture_set`...and it doesn't look like such a definition is in the code you posted. What do you expect `Capture_set` to contain and where do you define it? – ASGM May 13 '19 at 15:31
  • I thought that was how you were supposed to use prefetch_related based on other examples (https://stackoverflow.com/questions/9176430/django-does-prefetch-related-follow-reverse-relationship-lookup). But even with simply capture instead of capture_set I still an error (type object 'Capture' has no attribute 'split') – Blue May 13 '19 at 15:46

1 Answers1

1

I know is not the way you were looking for, but you can achieve this with values(). Let's suppose your related name is "captures"

import pandas


query = Species.objects.all().values('captures__pk', 'captures__species_name',
                                     'captures__total_capture', 'pk', 'length',
                                     'weight')
data = pandas.DataFrame.from_records(query)
Vareta
  • 26
  • 4