gpt4 book ai didi

python - ModelMultipleChoiceField 上的 Django 多值

转载 作者:太空狗 更新时间:2023-10-30 01:25:32 25 4
gpt4 key购买 nike

模型.py

class User(models.Model):
id = models.CharField(max_length=255)
name = models.CharField(max_length=255)
desc = models.TextField()
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now_add=True, null=True)

def __str__(self):
return self.user.name

我的表单.py

class PostsForm(forms.ModelForm):
user = forms.ModelMultipleChoiceField(
queryset=User.objects.all()
)
class Meta:
model = Posts
fields = '__all__'

在我上面的代码中,我的表单如下所示:

+------------+
|Select + |
+------------+
|John Doe |
|Jessica |
|Jessica |
|Alex Joe |
+------------+

不过这不是我想要的,因为可能有多个名称,而且我知道该值来 self 模型上的 def __str__

如何在我的字段上添加另一个 str so 将是:

+---------------------+
|Select + |
+---------------------+
| 012931 - John Doe |
| 012932 - Jessica |
| 012933 - Jessica |
| 012934 - Alex Joe |
+---------------------+

它包含下拉列表中的 id + name,或其他信息。

最佳答案

__str__ 上的 User 模型中,您可以按照 doc 中的说明进行操作.

def __str__(self):
return "{} - {}".format(self.id, self.user.name)

这里是self.id的一个例子,你可以在那里得到任何值,比如self.name等等。

关于python - ModelMultipleChoiceField 上的 Django 多值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50771539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com