从其他Models对象中填充选择



快问一下,我这一辈子都不知道如何让这个工作,需要一些帮助。

我需要能够查询另一个模型的对象在不同的模型中使用的选择。我正在考虑一个外键,但我真的不需要它来扩展其他模型。

我有一个名为Group的组,它将显示来自另一个名为Games的模型的选择。这些对象将已经保存在数据库中。我只是不知道如何显示选项。

Models.py对于我们试图在中显示选择的模型

game是我们希望从Games模型中选择的字段

from django.db.models.aggregates import Max
from games.models import Games

# Create your models here.
class Group(models.Model):
name = models.CharField(max_length=200)
game = models.ForeignKey(Games, on_delete=models.CASCADE)
size = models.IntegerField()
total_size = models.CharField(max_length=200)
play_time = models.DateTimeField()
description = models.TextField(max_length=200)
roles = models.CharField(max_length=200)
is_full = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name

Models.py从我们想要从中生成的选择我想从这个模型中使用name字段来选择Groupgame字段。

from django.db import models
from django.db.models.aggregates import Max

# Create your models here.
class Games(models.Model) :
GENRE_CHOICES = [
('Action', 'Action'),
('Acion-Adventure', 'Action-Adventure'),
('Adventure', 'Adventure'),
('MMO', 'MMO'),
('Puzzle', 'Puzzle'),
('Role Playing', 'Role Playing'),
('Simulation', 'Simulation'),
('Strategy', 'Strategy'),
('Sports', 'Sports')
]
RATING_CHOICES = [
('E', 'Everyone'),
('E10+', 'Everyone 10+'),
('T', 'Teen'),
('M', 'Mature 17+'),
('A', 'Adults Only 18+'),
('RP', 'Rating Pending')
]
PLATFORM_CHOICES = [
('Multi', 'Multi Platform'),
('PC', 'PC'),
('XBOX', 'XBOX'),
('Playstation', 'Playstation'),
('Nintendo', 'Nintendo')
]
name = models.CharField(max_length=200)
platform = models.CharField(max_length=20,
null=True,
choices=PLATFORM_CHOICES,
default='Select'
)
publisher = models.CharField(max_length=100)
genre = models.CharField(max_length=100,
null=True,
choices=GENRE_CHOICES,
default='Select'
)
rating = models.CharField(max_length=15,
null=True,
choices=RATING_CHOICES,
default='Select'
)
release_date = models.DateField()
tags = models.CharField(max_length=200)
picture = models.ImageField(
max_length=200,
default='games/default.png',
null=True,
upload_to='games/'
)
is_new = models.BooleanField(null=True)
is_popular = models.BooleanField(null=True)
is_featured = models.BooleanField(null=True)
def __str__(self):
return self.name

所以问题不在models.py中,而是在我的forms.py中,我没有为此定义一个ModelChoiceField。所以在forms。py中,我添加了这个:

class GroupForm(forms.ModelForm):
class Meta():
model = Group
fields = ['name', 'game', 'size', 'total_size', 'play_time', 
'description', 'roles']
game = forms.ModelChoiceField(queryset=Games.objects.all())

最新更新