0

I have this manager in my models.py

class ItemManager(models.Manager):
 def get_fee(self):
 from django.db import connection
    cursor = connection.cursor()
    cursor.execute("""
        SELECT fee
        FROM item
        WHERE itemID = %d AND item.type = %d 
        """, [self.myItemID, self.myItemType])
    fee = cursor.fetchone()
    return fee

and class

Sample(models.Model):
sampleID = models.AutoField(primary_key=True)
itemID = models.ForeignKey(Item)
item.type  = models.ForeignKey(Item)
    ...

def save(self, *args, **kwargs):
    is_new = self.pk is None
    super(Sample, self).save(*args, **kwargs)
    if is_new:
        cd.amount = MonthlyFeeManager() 
        cd.save()

Then it produces an error:

Cannot convert <myapp.models.ItemManager object at 0xa6f07ec> to Decimal

In general, i want to execute a RAW SQL query in a manager and use it to get the result from the query. I tried to search but most returns are tuples, not a value.

skinnyas123
  • 382
  • 1
  • 4
  • 13
  • 1
    You are misusing the Manager. In fact, all of this code looks strange. Is this your actual code or a generic example? The relations don't look correct and neither do the attribute names – jdi Sep 30 '12 at 14:59
  • This is just an example. You can ignore my code above. I just want cd.amount get a value from a different table in executing an sql query (or maybe there is another way). – skinnyas123 Sep 30 '12 at 15:03
  • Yes but we can't help you if your code example doesn't even remotely reflect what you are doing. You could simply do the query in the save method and assign the value to `amount`. But the approach would all be guesses for your application. – jdi Sep 30 '12 at 16:21

1 Answers1

1

This is not how you use a manager. Even with a perfectly normal class instance, your attempt wouldn't give you what you wanted: you would need to instantiate it and call get_fee() on the instance.

With a manager, you don't need to instantiate it, because that's already done for you as the objects attribute on the model. But you still need to call the relevant method:

cd.amount = Sample.objects.get_fee()

However, this still won't work. That's because you've referred to self.myItemId and self.myItemType, which don't exist on the Manager object. Which leads me to the conclusion that you don't want a Manager object at all: you just want a standard model method. And there's no need for the raw SQL, either: your code is perfectly easily expressed using normal model query syntax.

(I can't show you exactly what it would look like, because the ForeignKeys in your example don't make any sense, and it's not clear where fee is supposed to be coming from.)

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895