If i know company_id, how can i call a query list department, each department have list user and each user has username and staff_id? Example models and output below
class User(models.Model):
username=models.CharField(max_length=40,unique=True)
class Company(models.Model)
name=models.CharField(max_length=100)
users = models.ManyToManyField('User', through='User_Company',related_name="companies")
class Department(models.Model)
name=models.CharField(max_length=100)
users = models.ManyToManyField('User', through='User_Department',related_name="departments")
class User_Department(models.Model)
user = models.ForeignKey('User', on_delete=models.CASCADE,related_name="ud_membership")
department = models.ForeignKey('Department', on_delete=models.CASCADE,related_name="ud_membership")
class User_Company(models.Model)
user = models.ForeignKey('User', on_delete=models.CASCADE,related_name="uc_membership")
company = models.ForeignKey('Company', on_delete=models.CASCADE,related_name="uc_membership")
staff_id = =models.CharField(max_length=50)
I want data output with this format:
You can find the departments that have at least one useer in common with:
Department.objects.filter().
The .distinct()
clause [Django-doc] will prevent returing the Department
s multiple times. Without .distinct()
, each Department
will be returned that many times as there are common users.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.