Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

django - How to update model field after saving instance?

I have a Django model Article and after saving an instance, I want to find the five most common words (seedwords) of that article and save the article in a different model Group, based on the seedwords.

The problem is that I want the Group to be dependent on the instances of Article, i.e. every time an Article is saved, I want Django to automatically check all existing groups and if there is no good fit, create a new Group.

class Article(models.Model):
    seedword_group = models.ForeignKey("Group", null=True, blank=True)

    def update_seedword_group(self):
        objects = News.objects.all()
        seedword_group = *some_other_function*
        return seedword_group

    def save(self, *args, **kwargs):
         self.update_seedword_group()
         super().save(*args, **kwargs)

class Group(models.Model):
    *some_fields*

I have tried with signals but couldn't work it out and I'm starting to think I might have misunderstood something basic.

So, to paraphrase:

  • I want to save an instance of a model A.
  • Upon saving, I want to create or update an existing model B depending on A via ForeignKey.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Honestly I couldn't understand the rationale behind your need but I guess below code may help:

def update_seedword_group(content):
    objects = News.objects.all()

    """
        process word count algorithm and get related group
        or create a new group
    """
    if found:
        seedword_group = "*some_other_function*"
    else:
        seedword_group = Group(name="newGroup")
        seedword_group.save()
    return seedword_group

class Group(models.Model):
    *some_fields*

class Article(models.Model):
    seedword_group = models.ForeignKey("Group", null=True, blank=True)
    content = models.TextField()    

    def save(self):
        self.group = update_seedword_group(self.content)
        super().save()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...