0

Code: Models

class A1(models.Model):
    user = models.ForeignKey(User)
    field1 = models.CharField(max_length=200)
    field2 = models.CharField(max_length=200)

class A2(models.Model):
        user = models.ForeignKey(User)
        field1 = models.CharField(max_length=200)
        field2 = models.CharField(max_length=200)
        field3 = models.CharField(max_length=200)

Usage:

def insertRecord(modelName, fields, user)
    record = modelName(User=user, **fields)
    record.save()

Error: 'unicode' object is not callable.

Input: modelName: A2 fields: {u'field1': u'd2d2d2', u'field2': u'e2e2e2', u'field3': u'f2f2f2'} type(fields): 'dict'

Any solution/work around for this please ? Thanks,

1 Answer 1

1

You have to set attributes:

def insertRecord(modelName, fields, user)
    if modelName == "A1":
        record = A1(User=user)
    else:
        record = A2(User=user)

    for field, value in fields.iteritems():
        setattr(record, field, value)

or simply:

def insert_record(model_name, fields, user):
    cls = A1 if model_name == 'A1' else A2
    return cls(User=user, **fields)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your fast response. This helped a bit. But getting this as the error now: 'A2' object has no attribute 'getitem' @Daniel
so what's your fields-argument?
Field arguments are all of type: field1 = models.CharField(max_length=200). I am getting 'unicode' object is not callable error. Updated Code above. @Daniel
Any Suggestions Please ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.