Using many-to-many items before save()

226
February 03, 2020, at 1:20 PM

I am using models which has many-to-many fields

What I want to do is like this.

  1. Fetch items from web and store in memory

  2. Filter items. remove or add many-to-many field.

  3. Save in database.

my model

class Tweet(models.Model):
    text = models.TextField(null=True)
    genre = models.ManyToManyField(genre)

filter

tweets = fetchfromweb()
filtered = []
for tweet in tweets:
    if tweet.text == x :
        tweet.genre.add(genreObj)
        filtered.append(tweet)
    else:
        pass
for i in filtered: // write in db
    i.save()

However it shows error where tweet.genre.add(genreObj).

Without save(), I couldn't access many-to-many fields.

so for now my solution is like this.

tweets = fetchfromweb()
filtered = []
for tweet in tweets:
    tweet.save() ## save and create manytomanyfield
    if tweet.text == x :
        tweet.genre.add(genreObj)
        tweet.save()
    else:
        tweet.remove()

However it require many db insert and remove, is it good practice???

Or is there any good ideas ???

Answer 1

You can't add M2M records before tweet is saved because tweet needs to have a primary key to be set before adding M2M related records. You can check the docs.

Not sure if this gona work but you can try atomic transaction:

with transaction.atomic():
    for tweet in tweets:
        tweet.save() ## save and create manytomanyfield
        if tweet.text == x :
           tweet.genre.add(genreObj)
    else:
        tweet.remove()

Also, you do not need to call save again after adding M2M records.

Rent Charter Buses Company
READ ALSO
How can I see which .npmrc file is being currently used

How can I see which .npmrc file is being currently used

I am having very strange issues with my npm packages and installs

209
How can I send a large file between two Node servers using Socket.io

How can I send a large file between two Node servers using Socket.io

I'm writing a program that consists of two Node servers (well, one of them's an Electron application) that are connected with Socketio, and i'm looking for a way to send a large file (up to 10gb) from the socket server to the socket client over the socket...

191
How to reproduce the Mitre ATT&CK map using javascript

How to reproduce the Mitre ATT&CK map using javascript

I am using a product called ZoomData for dashboards and it works very well with custom javascriptI am trying to reproduce the ATT&CK Matrix for Enterprise at https://attack

123