user
user

Reputation: 445

Django return field for each model object

I have two models Game and People. I'm trying to iterate through the People model & return a single CharField for each value that people has & save their score with their name to the Game when creating the game. (Don't want name to be a field, just save with the score).

The error I'm currently getting with this is the following: no such column: home_game.score

class People(models.Model):
    name = models.CharField(verbose_name="Name", max_length=250)

    def __str__(self):
        return self.name

Game Model:

class Game(models.Model):
    title = models.CharField(verbose_name="Title", max_length=100)
    details = models.TextField(verbose_name="Details/Description", blank=False)
    for each in People.objects.all():
        score = models.CharField(verbose_name=each.title, max_length=4)
class GameCreateview(CreateView):
    model = Game
    fields = ['name', 'details', 'people']
    success_url = 'home/game/game_details.html'

Upvotes: 0

Views: 715

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21787

What you do here doesn't make sense:

for each in People.objects.all():
    score = models.CharField(verbose_name=each.title, max_length=4)

Firstly even if the loop works there would only be one score field in the end. Next a Django model is the reflection of a Database table. Ever heard of a table having an arbitrary number of columns (atleast a good normalized table)? No right? Since multiple People can be a part of a Game and have scores, you should have another table that reflects this relationship. Also to make querying easier use this table with a ManyToManyField [Django docs] as the through model:

class People(models.Model):
    name = models.CharField(verbose_name="Name", max_length=250)

    def __str__(self):
        return self.name

class Game(models.Model):
    title = models.CharField(verbose_name="Title", max_length=100)
    details = models.TextField(verbose_name="Details/Description", blank=False)
    people = models.ManyToManyField(
        People,
        through='PeopleGame',
        related_name='games'
    )

class PeopleGame(models.Model):
    game = models.ForeignKey(Game, on_delete=models.CASCADE)
    person = models.ForeignKey(People, on_delete=models.CASCADE)
    score = models.CharField(max_length=4)
    
    def __str__(self):
        return f"Game: {self.game.title}, Person: {self.person}, Score: {self.score}"

Note: Model names should ideally be singular, so use Person instead of People.

Upvotes: 1

Related Questions