如何在Django中过滤相关字段?

时间:2019-06-28 08:43:42

标签: python django django-models

说我有一个与模型公司有多对多关系的用户模型。以及模型UserType,它同时连接到User和Company。像这样:

class User(models.Model):
    name = models.TextField()

class Company(models.Model):
    name = models.TextField()
    users = models.ManyToManyField(User, related_name="companies")

class UserType(models.Model):
    name = models.TextField()
    company = models.ForeignKey(Company, related_name="user_types")
    users = models.ManyToManyField(User, related_name="user_types")

我想找到公司中的所有用户,这很简单:User.objects.filter(companies=some_company)。但是,我也想在返回的用户对象上过滤user_types字段,以便仅返回连接到给定Company的UserType对象。为了用代码解释它,它应该返回true:

def check_user_types(users, company):
    for user in users:
        for user_type in user.user_types:
            if user_type.company != company:
                return false
    return true

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我知道了。对于面临相同问题的任何人,这都可以解决:


    public class AddNewCase {
        WebDriver driver;

        public List<String> List1 = new ArrayList<>(); // Created from Method1
        public List<String> List2 = new ArrayList<>(); // Created from Method2

        public AddNewCase(WebDriver driver) {
            this.driver = driver;
            PageFactory.initElements(driver, this);
        }

        public void Method1() throws Exception {
            // ***some code***
            syso(List1) //Shows correct data
        }

        public void Method2() throws Exception {
            // ***some code***
            syso(List2) //Shows correct data
        syso(List1) // It shows blank data in this method, so the below if condition fails.
            if (List1.equals(List2)) {
                syso("testcase Pass")
            }
        }
    }