Inserting Facts into the Knowledge Base using Django

Inserting into a database is easy, but using an object relational mapper(ORM) such as the one included in Django make interaction with a database much easier.

Below is a function that inserts a fact into the django database if set up correctly. I will expand more on this later, but the code should give you an idea about how Django's ORM works

from website.kb.models import *

def insertFact(subject,relation,object,article_name,sentence):
    """
    All inputs are strings.
    Output is fact object.
    """
    sentence_obj = Sentence.objects.get_or_create(sentence=sentence)
    article_obj = Article.objects.get_or_create(name=article_name)
    subject_obj = NounPhrase.objects.get_or_create(noun_phrase=subject)
    relation_obj = Relation.objects.get_or_create(relation=relation)
    object_obj = NounPhrase.objects.get_or_create(noun_phrase=object)
    
    fact = Fact.objects.get_or_create(subject=subject_obj,
                                      relation=relation_obj,
                                      object=object_obj,
                                      article=article_obj,
                                      sentence=sentence_obj)
    return fact

Insertion could be done more quickly if you only updated the article_obj when you moved to a new article.