简体   繁体   中英

Get object or all in django query_set

I have a model like this:

class Product(models.Model):
    name = models.CharField(_('name'))
    ...
    user = models.ForeignKey(User, related_name='products', on_delete=models.CASCADE, verbose_name=_('user'))
    ...

and i want:

if the user authenticated:

return the user products

else if user did not authenticate:

return all products

in linq C# we can solve this problem with:

Product.Where(!request.user.is_authenticated() || user.id == request.user.id)

i know that in python can solve it with if else :

if request.user.is_authenticated:
    return Product.objects.filter(user=request.user)

else:
    return Product.objects.all()

Question : is there a solution like the C# linq?

There is, but it's pretty ugly:

return Product.objects.filter(**{'user': request.user}
    if request.user.is_authenticated else **{})

I think the if/else solution is better.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM