Designing code to handle transfers of objects called “contractBundles”. Have this in the models.py in a “contract” app:
class contractBundleManager():
# def trade(self, buyer, seller, amount):
def add (self, user=pgamedb_models.Player, contractName=str, amount=float):
contractList = contract.objects.all()
for c in contractList:
if contractName == c.contractText:
user.money = user.money - (amount * c.value)
return self.create(contract=c, volume=amount, owner=user)
class contractBundle(models.Model):
objects = contractBundleManager()
contract = models.ForeignKey('contract')
volume = models.FloatField()
owner = models.ForeignKey(pgamedb_models.Player)
def __str__(self):
return '%10.2f x %s -> %s' % (self.volume, self.contract.shortName, self.owner.user.username)
Elsewhere, I want to let people purchase the bundles by pressing a button:
from contracts import models as cmodels
...
if request.method == 'POST':
...
elif 'Buy' in request.POST:
[set up activeUser, polName, amount]
cmodels.contractBundle.objects.add(user=activeUser, contractName=polName, amount=amount)
Yet when the code calls the contractBundle.objects.add() method, I get the following error:
AttributeError at [url]
'Manager' object has no attribute 'add'
Request Method: POST
Request URL: [url]
Django Version: 1.3.1
Exception Type: AttributeError
Exception Value:
'Manager' object has no attribute 'add'
Exception Location: ...views.py in [method], line 56
Python Executable: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.1
Any thoughts why this might be happening?
There are a couple of things here that are wrong.
Firstly, your manager class needs to inherit from models.Manager:
This is where all the code like
createis defined.Also, it seems like a really bad idea to use classes/types as default values for function parameters. If you want to document what types a function needs, you should use a docstring.
Edit after comment No, I’m not referring to the return statement or the way you’re calling
self.create. I’m referring to the default values in thecontractBundleManager.addmethod. You should never do this. If someone calls your method without passing theuserparameter, the function will use the default value you have defined – which is a class. Classes in Python are mutable, so your function will actually modify the definition of thePlayerclass.Really, this is not the way to show the correct types to call the function with. Leave out the default values, and use a docstring.