我在django应用程序中创建了一个公司,两个或更多人可以登录同一家公司。我想向公司的其他用户显示公司一个用户的数据。
简化:如果公司的一个用户创建了一个对象,那么该公司的所有用户都应该可以看到该对象
但是我在提取数据时遇到问题
Models.py
class ItemBatch(models.Model):
uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='uploaded_by')
name = models.CharField(max_length=100)
pid = models.IntegerField(blank=True)
quantity = models.IntegerField(blank=True)
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='ship_company')
class User(AbstractUser):
is_supplier = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
email = models.EmailField(default=False)
class Company(models.Model):
company_name = models.CharField(max_length=255, default=0)
company_email = models.EmailField(max_length=255, default=0)
company_phone = models.CharField(max_length=255, default=0)
company_code = models.IntegerField(default=0)
Views.py
class allordersview(viewsets.GenericViewSet, mixins.ListModelMixin):
queryset = ItemBatch.objects.all()
serializer_class = holdSerializer
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
queryset = queryset.filter(uploaded_by_id=request.user) # ??Changes??
.
.
return Response(serializer.data)
如何更改查询集,使其显示公司的所有项目批次?
你可以做
queryset.filter(uploaded_by__teacher__company=request.user.teacher.company)
PS:而不是覆盖list
方法覆盖get_queryset
方法并在那里应用过滤器,例如
def get_queryset(self):
return ItemBatch.objects.filter(uploaded_by__teacher__company=self.request.user.teacher.company)