[Answered ]-Models.py with ManyToMany and progmatically adding data via a shell script

0👍

.filter returns a list, when you need is a single object, so you should use .get(client=item['client'])

👤Tiago

2👍

Turns out Tiago was very close..

# Assume the client "clientspec" exists.  I know how to create that if 
neeeded. 
changes = [ { 'change': 123, 'desc': "foobar", status': "foobar", 
client': "clientspec", }] 
for item in changes: 
  entry = Change()
  entry.change  = item['change']
  entry.desc    = item['desc']
  entry.status  = item['status']
  entry.time    = datetime.datetime.fromtimestamp(float(item['time']))
  entry.client.add(Client.objects.get(client=item['client']))
  entry.save()

So.. I will give props to Tiago

0👍

I tried the code but i got error

ValueError: "<Change: 123 -- foobar>" needs to have a value for field "change" before this many-to-many relationship can be used

Manytomany(entry.client.add) can be used only after saving the field ie entry.save()

There may be a lot of clients so you can use:

changes = [{'change': 123, 'desc': "foobar", 'status': "foobar", 
'client': ("client1","client2"),},{......] 
for item in changes: 
    entry = Change( 
        change    = item['change'], 
        desc    = item['desc'], 
        status    = item['status'],)
    entry.save()
    for c in item['client']:
        entry.client.add(Client.objects.get(client=c))

Leave a comment