bennylope / django-organizations

:couple: Multi-user accounts for Django projects
http://django-organizations.readthedocs.org/
BSD 2-Clause "Simplified" License
1.31k stars 212 forks source link

How to only list objects belonging to an organization #225

Closed btzs closed 3 years ago

btzs commented 3 years ago

Hi! I only want to list objects belonging to the organization. How can I change the queryset of my class based view?


**models.py**
class Item(models.Model):
    # Relationships
    company = models.ForeignKey(
        'organizations.Organization',
        related_name='items',
        on_delete=models.CASCADE
    )

    # Fields
    created = models.DateTimeField(auto_now_add=True, editable=False)
    cust_item = models.TextField(max_length=100)

**views.py**
class ItemListView(generic.ListView):
    model = models.Item
    form_class = forms.ItemForm

    def get_queryset(self):
        return models.Item.objects.all()

I think this is covered in the documentation, but unfortunately I cannot get it to work:

You can simplify access checks with a queryset method.:

class ProductQuerySet(models.QuerySet):
    def for_user(self, user):
        return self.filter(account__users=user)

Views & mixins

The views in the rest of your application can then filter by account.:

class OrganizationMixin(object):
btzs commented 3 years ago

Sorry I missed a similar issue. https://github.com/bennylope/django-organizations/issues/137#issuecomment-326670870 I will try that first