Please help with queryset for related_name!

I am trying to make a query that is way too complicated for my novice Django skills…

I would like to query a list of products (Product model) that haven’t been listed (Listing model) by a specific facebook account (FacebookAccount).

class Product(models.Model):
    sku = models.CharField(max_length=100, unique=True)
    title = models.CharField(max_length=255, null=True, blank=True)
    mark_as_complete = models.BooleanField(default=False)

class Listing(models.Model):
    product = models.ForeignKey(Product, related_name='listings', on_delete=models.CASCADE, null=True, blank=True)
    facebook_account = models.ForeignKey(FacebookAccount, related_name='facebook_account', on_delete=models.CASCADE, null=True, blank=True)
    listing_price = models.DecimalField(decimal_places=2, max_digits=10, null=True, blank=True)`
    location = models.CharField(max_length=255, null=True, blank=True)

My queryset is:

def get_queryset(self):
        #listings = Listing.objects.filter(facebook_account__slug=self.kwargs.get('slug'))
        queryset = Product.objects.filter(mark_as_complete=True)
        return queryset

Thanks in advance for any help! I have about 6 hours into this so far with no luck with anything I’ve tried.

For clarity - you want every Product not related to a Listing by the product FK in Listing. Am I understanding this correctly?

If so, try Product.objects.filter(listing=None)

Thanks again, Ken!

This returns almost what I need. But now I need it to return products not listed by a specific facebook_account…

The following returns products that are not listed but not specific to facebook_account.

def get_queryset(self):
        listings = Listing.objects.filter(facebook_account__slug=self.kwargs.get('slug'))
        queryset = Product.objects.filter(mark_as_complete=True).filter(listings=None)
        return queryset

As you’ve already used, keep in mind that you can chain filter clauses - and don’t forget about the exclude clause.

1 Like

I was able to get it working with:

def get_queryset(self):
    listings = Listing.objects.all()
    queryset = Product.objects.filter(mark_as_complete=True).exclude(listings__facebook_account__slug=self.kwargs.get('slug'))
    return queryset

Thank you for your help!

1 Like