从其他模型对象填充选择
快速问题,我无法为自己的一生而弄清楚如何使它起作用并需要一些帮助。
问题 我需要能够查询另一个模型的对象以在其他模型中进行选择。我当时正在考虑一个外键,但我真的不需要它扩展其他模型。
我有一个称为 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
model.py从模型中我们要生成 的选择
我想在此模型中使用 name
字段,以在 group
game
字段上的选择上进行选择。
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,问题不是在模型中。所以以我的形式。
So the issue was not in the models.py but in my forms.py I was not defining a ModelChoiceField for this. So in my Forms.py I added this: