ForeignKey django 1.1.1 model
I have
class staff_name(models.Model):
firstname = models.CharField(max_length=150)
surname = models.CharField(max_length=150)
class inventory_transaction(models.Model):
staffs = models.ForeignKey(staff_name)
I want to get or create staff surname and first name through inventory_transaction
I used these code below
inventory_transaction.objects.get_or_create(staffs__surname__contains=sname,staffs__firstname__c开发者_如何学JAVAontains=fname)
I got this error "staffs__surname__contains can not be defined"
What have i done wrong ?
thanks
Hmm based on the documentation of get_or_create()
:
In English, that means start with any non-'defaults' keyword argument that doesn't contain a double underscore (which would indicate a non-exact lookup).
I would say what you want to do is not possible as your query could return more than one result. The arguments passed to get_or_create()
must be in a way that a unique result is returned.
You could try __exact
instead of __contains
:
inventory_transaction.objects.get_or_create(staffs__surname__exact=sname,staffs__firstname__exact=fname)
But I don't think that get_or_create()
can create foreign key objects automatically.
So probably the easiest thing in this case is this:
try:
itrans = inventory_transaction.objects.get(staffs__surname__contains=sname,staffs__firstname__contains=fname)
except inventory_transaction.DoesNotExist:
staff = staff_name(firstname=fname, surname=sname)
staff.save()
itrans = inventory_transaction(staffs=staff)
itrans.save()
Btw common practice is to use capital names for classes and I wouldn't use underscores as they are also used in DB lookups. That said, rename your classes to StaffName
and InventoryTransaction
精彩评论