Take the 2-minute tour ×

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


I got this error "staffs__surname__contains can not be defined"

What have i done wrong ?


share|improve this question
@Spikie: Here's request; Please Use Upper Case Letters for Proper Nouns like "I". You can update your question to make it readable, you might get better answers if you question looks good. –  S.Lott Mar 31 '10 at 14:07
Ok ...Ok Thanks –  Spikie Mar 31 '10 at 14:12
add comment

1 Answer

up vote 2 down vote accepted

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:


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:

    itrans = inventory_transaction.objects.get(staffs__surname__contains=sname,staffs__firstname__contains=fname)
except inventory_transaction.DoesNotExist:
    staff = staff_name(firstname=fname, surname=sname)
    itrans = inventory_transaction(staffs=staff)

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

share|improve this answer
Ok Thanks Felix ! –  Spikie Mar 31 '10 at 15:32
add comment

Your Answer


