Christopher Kinyua
Christopher Kinyua

Reputation: 170

Django On-Insert trigger

I have a model in Django which I want to be automatically populated with values once another model has objects inserted. This is the originator model Question:

class Question(models.Model):
question = models.CharField(max_length=200, null=False, blank=False)
description = models.TextField('description', default=False)
voters = models.ManyToManyField(User, related_name='+')
votes = models.IntegerField(default = 0)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)

Question View:

class QuestionApiView(AuthenticatedAPIView):
"""
Lists all questions or creates a new question
"""

def post(self, request, format=None):

    vote_data = request.data
    vote_data["created_by"] = request.user.id

    data["created_by"]=request.user.id

    print(vote_data)
    print(vote_data["voters"])
    voter_data = vote_data["voters"]

    result, valid = QuestionHelper.createQuestion(vote_data)

Question Helper:

class QuestionHelper(object):
@classmethod
def createQuestion(klass, questiondata):
    """
    creates a question
    """
    createdQuestion = QuestionSerializer(data=questiondata)
    if createdQuestion.is_valid():
        createdQuestion.save()
        return createdQuestion.data, True
    return createdQuestion.errors, False

Question Serializer:

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = '__all__'

This is my Choice model which I want the values Yes, No and Abstain added onto choice_text once a Question object is created:

question = models.ForeignKey(Question, on_delete=models.CASCADE, default=1)
choice_text = models.CharField("choice", max_length=250)

This way, each Choice will be linked to a Question using the question_id

Upvotes: 1

Views: 668

Answers (1)

Daniel
Daniel

Reputation: 3527

Here is an example using choice options:

models.py

YES = 0
NO = 1
ABSTAIN = 2

CHOICE_OPTIONS = (
    (YES, 'yes'),
    (NO, 'no'),
    (ABSTAIN, 'abstain'),
)

class Question(models.Model):
    choice = models.PositiveIntegerField(..., choices = CHOICE_OPTIONS)

views.py

from . import models

# update a choice instance:
question = models.Question.objects.get(id='<the id>')
question.choice = models.YES
question.save()

Upvotes: 1

Related Questions