Django模型:从对象中获取用户

时间:2020-12-13 19:35:12

I just started with Django, I love it! It still is quite challenging however. I have a model Shift that has users assigned to it with the model Assign. I want to get all the users that are assigned to a certain shift, but I can only get the Assign objects. Do you guys know how I should change my query?

我刚开始使用Django,我喜欢它!然而,它仍然非常具有挑战性。我有一个模型Shift,用户使用模型Assign分配给它。我希望获得分配给某个班次的所有用户,但我只能获得Assign对象。你们知道我应该如何改变我的查询吗?

The problem above gives me these 2 models:

上面的问题给了我这两个模型:

class Shift(models.Model):
    shift_location = models.CharField(max_length=200)

    def get_shift_users(self):
        Assign.objects.filter(shift=self)


class Assign(models.Model):
    shift = models.ForeignKey(Shift, unique=False)
    user = models.ForeignKey(User, unique=False)

How do I return all users with the method get_shift_users, instead of all Assign objects? I thought that

如何使用方法get_shift_users而不是所有Assign对象返回所有用户?我以为

Assign.objects.filter(shift=self).user

Would work...

会工作...

1 个解决方案

#1


1  

Starting from User

从用户开始

def get_shift_users(self):
   return User.objects.filter(assign_set__shift=self)

#1


1  

Starting from User

从用户开始

def get_shift_users(self):
   return User.objects.filter(assign_set__shift=self)

相关文章