gpt4 book ai didi

python - 基于同一模型中的另一个外键动态限制 Django 模型中外键的​​选择

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

我有这些模型:

class UserProfile(models.Model):
name = models.CharField(max_length=100)

class Dialog(models.Model):
belong_to = models.ManyToManyField(UserProfile)

class Message(models.Model):
# Dialog to which this message belongs
part_of = models.ForeignKey(Dialog)

# User who sends message
sender = models.ForeignKey(UserProfile, related_name='sender')
# User who receives message
receiver = models.ForeignKey(UserProfile, related_name='receiver')

我想做的是限制发送者和接收者字段的选择,使它们只能是整个对话框所属的用户。我试过这个:

sender = models.ForeignKey(UserProfile,
related_name='sender',
limit_choices_to={'dialog':1})

这限制了选择,但仅限于 id=1 的对话成员。我想知道这是否可以动态完成?

最佳答案

我认为没有任何方法可以像您希望的那样使用 limit_choices_to 进行动态过滤,因为您将无权访问所需的对象以在那里形成这样的查询。

相反,您可能应该为消息创建自己的模型表单,并在那里为这些字段设置查询集。像下面这样的东西......

class MessageForm(forms.ModelForm):
class Meta:
model = Message

def __init__(self, *args, **kwargs):
super(MessageForm, self).__init__(*args, **kwargs)

if self.instance.part_of and self.instance.part_of.id:
users = self.instance.part_of.belong_to.all()
self.fields['sender'].queryset = users
self.fields['receiver'].queryset = users

此外,为什么 limit_choices_to 适用于您的示例,但不是动态有用的。

Django 只是将 limit_choices_to 表达式处理为一个额外的过滤器,以应用于 ModelForm 字段查询集。您的表达式 {dialog: 1} 在语义上与您将 UserProfile.objects.filter(dialog=1) 的结果分配给我的示例中的查询集没有什么不同.

Django 不知 Prop 有该 ID 的对话框是否作为关系存在于 UserProfile 中,它只是应用过滤器。在这种情况下,存在一个 id 为 1 的对话框,因此它可以正常工作。相反,如果您在示例中粘贴了一个无效的对话框 ID...它将评估为一个空查询集,您将在表单中获得 0 个选择。

它不能是动态的,因为在 limit_choices_to 中,您只能为 UserProfile 模型创建一个过滤器表达式。您无权访问该字段所属的 Message 实例,也无权访问该消息所属的 Dialog 模型...因此您无法创建过滤器来动态限制这些实例。

创建您自己的 ModelForm 并限制该字段的查询集,这是您拥有所需信息的正确方法。

关于python - 基于同一模型中的另一个外键动态限制 Django 模型中外键的​​选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29255812/

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