Costas Vassilopoulos
Costas Vassilopoulos

Reputation: 33

How can I create a Django OneToMany Relation?

So, I have been making my first website and hosting it on Heroku. The website's purpose is to post challenges which lead to a specific secret key(kinda like a very easy CTF). When the key is submitted, the challenge is solved.

This is the code in my models.py file

from django.db import models
from django.contrib.auth.models import User


class Post(models.Model):
    """ Each post represents one challenge """
    title = models.CharField(max_length=40)
    text = models.TextField()
    secret_key = models.CharField(max_length=30)
    solved = models.BooleanField(default=False, name='solved')
    file = models.FileField(upload_to='uploads/', null=True, blank=True)
    # solved_by = models.ForeignKey(User, on_delete=models.CASCADE)

    def check_state(self, answer):
        """ Examine whether the challenge was solved """
        if self.secret_key == answer:
            self.solved = True
            self.save()
            return True
        return False

    def __str__(self):
        return self.title

Each post is basically a challenge. The solved value is set to True when somebody solves the challenge/post and also controls whether the text is visible to the users. Right now, when someone solves a challenge it is being solved for everybody else. I want each user to solve every challenge and has his own solved variable for each challenge. I tried using models.Foreign key, but it won't work. What database relation do I need in order to make this work?

Upvotes: 3

Views: 68

Answers (1)

Kermit
Kermit

Reputation: 5992

Sounds like you need a many-to-many UserPost table between your Post and User models.

https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/

That way you can have a unique relationship between every user and every challenge.

FYI. You can make single line comments with # although I understand the descriptive approach that you are trying to follow.

Upvotes: 1

Related Questions