query in query django - django

how to make such query in django.
I have Site model where I can find relation to the topic model. In topic model I can fing relation to the post model. I want to extract post from a site having information only about site, not a topic. What is more posts have to starts with query.
query = request.GET.get('query','')
iweb_obj = IWeb.objects.get(id=iweb_id)
topics = Topic.objects.filter(iweb=iweb_obj)
iweb_posts = []
for t in topics:
posts = Post.objects.filter(topic=t)
for p in posts:
iweb_posts.append(p)
iweb_posts = iweb_.filter(content__istartswith=query)
I have an error that iweb_posts isnt query set and I cant make such action. It is quite obvious, however I do not have idea how to make it works ? I've heard that I can use filter(**kwargs) but I do not know how to use it ?

Your logic looks a little funky since you're overwriting posts each time in the topic loop. You can accomplish what you need without loops and lists using only query set filters (I've added an __in filter, for example):
query = request.GET.get('query','')
iweb_obj = IWeb.objects.get(id=iweb_id)
topics = Topic.objects.filter(iweb=iweb_obj)
iweb_posts = Post.objects.filter(topic__in=topics).filter(content__istartswith=query)

Related

How to mix multiple querysets into one and re order them by time created?

I am learning Django and still a beginner. For practising, i am trying to make a demo social media website. In my project, users can create groups, then they can post and comment there. In the home page, i am trying to add a section like 'recent activities' where a user can see recent activities in that website like "John created a group 'Javascript', Tim posted a comment in 'Python', Sarah posted in 'CSS'" Now i have made some queries like:
groups = Group.objects.all().order_by('-created')[0:5]
posts = Post.objects.all().order_by('-created')[0:5]
comments = Comment.objects.all().order_by('-created')[0:5]
I want to mix them all in a single queryset. Then order them all by the time they were created. I know it's a silly question and i have been stuck here since morning. Can you help me and show me the process please?
You can chain these together and order by the created field with:
from operator import attrgetter
groups = Group.objects.order_by('-created')[:5]
posts = Post.objects.order_by('-created')[:5]
comments = Comment.objects.order_by('-created')[:5]
all_items = sorted(
[*groups, *posts, *comments],
key=attrgetter('created'),
reversed=True
)
Now all_items is a hetrogenous list with different types of objects. This will thus make the rendering process a bit more complicated since a comment probably has different fields than a Post for example.
You can also use chain function from itertools module to combine the querysets and then sort them in reverse order using the created field as key.
from itertools import chain
groups = Group.objects.all()[0:5]
posts = Post.objects.all()[0:5]
comments = Comment.objects.all()[0:5]
queryset = sorted(
chain(groups, posts, comments),
key=lambda instance: instance.created,
reverse=True
)

Retrieve extra fields with Graph API using PHP

I'm trying to create some social dashboard and therefore I want to retrieve my posts from my page. When I use this one to fetch my posts, it doesn't return me all the information I need (e.g 'picture', 'full_picture', 'attachments')
$user_posts = $facebook->api('/me/posts', 'GET');
print_r($user_posts);
But when I try next one, it still doesn't return me my required information:
$user_posts = $facebook->api('/me/posts?{created_time,id,message,full_picture,picture,attachments{url,subattachments},likes{name},comments{from,message,comment_count,user_likes,likes{name}}}', 'GET');
print_r($user_posts);
Anyone ideas??
I know that this has been asked a long time ago, but maybe useful for someone:
After - me/posts? - you need to make sure to put fields= and then a list of fields required.
So this would be:
$user_posts = $facebook->api('/me/posts?fields={created_time,id,message,full_picture,picture,attachments{url,subattachments},likes{name},comments{from,message,comment_count,user_likes,likes{name}}}', 'GET');
print_r($user_posts);

Filter out multiple emails from a Queryset

I'm trying to filter out multiple emails from a queryset in order to stop our employee emails from affecting any exports. I have the following in settings.py:
EMAIL_FILTERS = ['email1', 'email2']
and I'm trying to use this to filter out any entries in the DB with our emails in the following query:
EMAIL_FILTERS = getattr(settings, 'EMAIL_FILTERS')
campaigns = CampaignsSignup.objects.filter(created_date__gte=self._get_start_date(dte),
created_date__lte=self._get_end_date(dte)).order_by('-created_date')
However after trying Q and exclude I can't seem to get it to work. I should also note as much as I would like to be able to use endswith some of the employees are using their personal email address so at the moment it wouldn't be viable.
Thanks.
I see you've found a solution, but the normal way to do this is with exclude:
campaigns = CampaignsSignup.objects.filter(
created_date__gte=self._get_start_date(dte),
created_date__lte=self._get_end_date(dte)
).order_by('-created_date').exclude(email__in=SAVCHAMP_EMAIL_FILTERS)
After throwing everything at it I stumbled upon a way of doing it. Using __in with Q correctly filters out the emails that have been included in the email_filter list in settings.
campaigns = CampaignsSignup.objects.filter(~Q(email__in=SAVCHAMP_EMAIL_FILTERS), created_date__gte=self._get_start_date(dte),
created_date__lte=self._get_end_date(dte)).order_by('-created_date')

Django: Querying comments based on object field

I've been using the built-in Django comments system which has been working great. On a particular page I need to list the latest X comments which I've just been fetching with:
latest_comments =
Comment.objects.filter(is_public=True, is_removed=False)
.order_by('submit_date').reverse()[:5]
However I've now introduced a Boolean field 'published' into the parent object of the comments, and I want to include that in the query above. I've tried using the content_type and object_pk fields but I'm not really getting anywhere. Normally you'd do something like:
Comment.objects.filter(blogPost__published=True)
But as it is not stored like that I am not sure how to proceed.
posts_ids = BlogPost.objects.filter(is_published=True).values_list('id', flat=True) #return [3,4,5,...]
ctype = ContentType.objects.get_for_model(BlogPost)
latest_comments = Comment.objects.filter(is_public=True, is_removed=False, content_type=ctype, content_object__in=posts_ids).order_by('-submit_date')[:5]
Comments use GenericForeignKey to store the relation to parent object. Because of the way generic relations work related lookups using __<field> syntax are not supported.
You can accomplish the desired behaviour using the 'in' lookup, however it'll require lot of comparisons when there'll be a lot of BlogPosts.
ids = BlogPost.objects.filter(published=True).values_list('id', flat=True) # Get list of ids, you would probably want to limit number of items returned here
content_type = ContentType.objects.get_for_model(BlogPost) # Becasue we filter only comments for BlogPost
latest_comments = Comment.objects.filter(content_type=content_type, object_pk__in=ids, is_public=True, is_removed=False, ).order_by('submit_date').reverse()[:5]
See the Comment model doc for the description of all fields.
You just cannot do that in one query. Comments use GenericForeignKey. Documentation says:
Due to the way GenericForeignKey is implemented, you cannot use such
fields directly with filters (filter() and exclude(), for example) via
the database API.

How do i get (if possible) a queryset order by a parent entry and all child entries and so on?

I don't know if i was describing things the right way in the headline, so i will try to do it better here,
Lets say that i am building a forum system and that i have a Post model that has, among other fields, a Foreign key to the Thread model and a foreign key to self so with the name of parent_post, so people will be able to post replies to other posts or start new posts for each thread.
Every thing is working great. The thing i don't know and can't find is how to show the posts in order when i want to show all posts for a thread....
For example:
Thread x:
post a .....
response to post a .....
response number 2 to post a .....
post b ....
post c ....
response to post c .....
response 2 to post c .....
And so on......
I know how to do it in pure SQL and i also know there i can return all thread posts and set them up in order with JS but there must be a way to do it the django way :-)
Thank you,
Erez
I guess your model looks like:
class Post(Model):
....
thread = ForeignKey(Thread)
post = ForeignKey('self')
posttime = DateTimeField(auto_now_add=True)
You will get all mother-posts belong to a thread...
mothers = Post.objects.filter(thread=x, post__isnull=True)
post__isnull=True will filter posts that have no referance to self, which means they are posts that starts the topic...
Then Get posts belong to a single topic and order them...
mother-post = mothers[0]
childs = Post.objects.filter(post=mother-post).order_by('posttime')
But probably, ordering by id (which is default) also solves your problem so, you may not need order_by .
UPDATE:
Yes you can do it in one query Such as for the post with id=12323,
Posts.objects.filter(Q(pk=12323) | Q(post__id=12323))
Link for documentation... That will do what you need.
You have to setup ordering = ['id',] or ordering = ['timestamp',] in your Post model.
When you will do request posts = Post.models.filter(thread=x) all post will be order by 'id' or by 'timestamp' fields. And when you will do posts[a].response_set.all() you will got all responses that ordered according your settings in model Meta class.
PS: sorry for my English
why not have a look at http://www.djangopackages.com/grids/g/forums/