Django如何获得不在many2many领域的用户?

时间:2019-04-07 15:15:54

标签: django django-models django-forms

'models.py'

class StaffProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile")
    staff_user = models.ManyToManyField(User, null=True, blank=True, related_name="staff_user")
    mobile_number = models.CharField(max_length=14, validators=[RegexValidator(r'^\d{1,10}$')])
    fcm_token = models.CharField(max_length=256, null=True, blank=True)
    manager = models.BooleanField(default=False)

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

'forms.py'

class ManagerSignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, label='Name')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
    mobile_number = forms.CharField(max_length=14, min_length=10, )
    staff_user = forms.ModelMultipleChoiceField(queryset=User.objects.filter(is_staff=False),required=True)

    def __init__(self, *args, **kwargs):
        all_user_list = User.objects.filter(is_superuser=False,is_staff=True)
        all_staff_profile = StaffProfile.objects.get(staff_user__in=all_user_list)

        super(ManagerSignUpForm, self).__init__(*args, **kwargs)
        # self.fields['staff_user'] = forms.ModelChoiceField(queryset=after_exclude)

我想显示(附加)整个StaffProfile模型的staff_user(M2M)字段中还不存在的用户。

注意:我正在扩展用户模型

2 个答案:

答案 0 :(得分:3)

使用isnull=True过滤器

User.objects.filter(staff_user__isnull=True)

答案 1 :(得分:1)

您可以通过M2M关系的In [105]: from pydicom.data import get_testdata_files # read a sample image In [106]: filename = get_testdata_files('MR_small.dcm')[0] ...: ds = pydicom.dcmread(filename) In [107]: data = ds.pixel_array In [108]: type(data) Out[108]: numpy.ndarray In [109]: data.shape Out[109]: (64, 64) In [111]: from skimage.transform import resize In [114]: IMG_PX_SIZE = 32 # resize to new size In [115]: resized_img = resize(data, (IMG_PX_SIZE, IMG_PX_SIZE), anti_aliasing=True) In [116]: resized_img.shape Out[116]: (32, 32) 来过滤用户,如下所示:

related_name