根据特定的group_name过滤ForeignKey(user)模型

时间:2019-03-18 11:48:49

标签: django django-models django-forms

在Django中,我创建了一个使用USER模型数据的模型 它保存了所有用户ID表单数据库,但被某些组过滤了

  

userId = models.ForeignKey(User,on_delete = models.CASCADE)

model.py

**from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Review(models.Model):
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=100, blank=True)
    reviewText = models.TextField(max_length=500, blank=False)
    timeStamp = models.DateTimeField(auto_now_add=True, auto_now=False)

    def __unicode__(self):#for python <2
        return self.name

    def __str__(self):#for python 3
        return self.name**

form displayed(with all user_id)

1 个答案:

答案 0 :(得分:0)

如果要过滤外键选择,可以在模型字段中使用limit_choices_to,如下所示:

class Review(models.Model):
    userId = models.ForeignKey(User, limit_choices_to={'groups__name': 'Your Group Name'}, on_delete=models.CASCADE)