Steven Matthews
Steven Matthews

Reputation: 11295

ValueError: "..." needs to have a value for field "..." before this many-to-many relationship can be used

I am getting this error:

try:
    newthing1 = Thing1()
    newthing1.thing1 = data['thing1']
    newthing1.save()
except (SystemExit, KeyboardInterrupt):
    raise
except Exception, e:
    clientnamedb_logger.error('Exception:', exc_info=True)
clientnamedb_logger.debug('create account - thing1 record created, thing1 id:%s' % newthing1.id)
#
# create an instance of Thing2 and save the thing2 record
#
try:
    newthing2 = Thing2()
    newthing2.target_id = target_id
    newthing2.thing2_id = user_id
    #newthing2.thing1 = data['datasharing_thing1']
    newthing2.thing1 = [newthing1.id]
    newthing2.save()
except (SystemExit, KeyboardInterrupt):
    raise
except Exception, e:
    clientnamedb_logger.error('Exception:', exc_info=True)

Now, I know that it is because newthing2 doesn't exist yet when trying to save the many to many relationship. I've tried executing a save right before assigning the list of newthing1.id, but that gives a null field constraint (I could turn that off, but I think that would give me two rows in my database, which I do not want).

How do I save a row with the data for newthing1.id on the newthing2.thing1 field, which is ManyToMany? Is there a way to do this without saving it twice? Will that create a duplicate row?

Upvotes: 1

Views: 3613

Answers (1)

siracoj
siracoj

Reputation: 101

Try to save without committing, that way you get the ID before you commit, like so:

     newthing1.save(commit=False)

After that you can use the id, but you will have to save again after thing 2 is saved:

     newthing2.thing1 = [newthing1.id]
     newthing2.save()
     newthing1.save()

Upvotes: 1

Related Questions