I'm building a fairly basic inventory management system with Django, and am trying to query my "Transaction" table to return only the most recent transaction_date for each pig_number (and the corresponding location_name).

The error I'm getting is 'Transaction' object is not iterable'

I feel like this should be easy but I'm trying to learn SQL, Python and Django all at once and am getting nowhere!

models.py:

class Locations(models.Model):
    location_name=models.CharField(max_length=13,primary_key=True)
    location_address=models.TextField()

    def __str__(self):
        return self.location_name

class Pig(models.Model):
    pig_number=models.CharField(max_length=4,primary_key=True)
    pig_type=models.CharField(max_length=8)
    pig_owner=models.CharField(max_length=4)
    pig_in_use=models.BooleanField()
    pig_purchase_date=models.DateTimeField('Date Purchased / Commissioned', default=now())

    def __str__(self):
        return self.pig_number

class Transaction(models.Model):
    transaction_date=models.DateTimeField('Processing Date',default=now())
    pig_number = models.ForeignKey(Pig, default=1,verbose_name="Pig Number", on_delete = models.SET_DEFAULT)
    location_name = models.ForeignKey(Locations, default="CQPL", verbose_name="Location Name", on_delete=models.SET_DEFAULT)

    class Meta:
        get_latest_by = 'transaction_date'

    def __str__(self):
        return "At "+str(self.transaction_date) +" pig number "+ str(self.pig_number)+ " was sent to "+ str(self.location_name)

This is where it's going wrong somehow (at least I think so). I've tried a couple of different expressions for 'result,' this being the most simple.

views.py


    result=Transaction.objects.latest()

    return render(request=request,
                  template_name="main/transactions.html",
                  context={"Transaction": result})```

0 Answers