Serialize Queryset - Group by date - django

I've got a model that looks something like:
class Deal(models.Model):
sender = models.ForeignKey(settings.AUTH_USER_MODEL)
created_on = models.DateField(auto_now_add=True)
recipient = modes.ForeignKey(settings.AUTH_USER_MODEL)
...
I'd like to get the daily count of deals sent or received by a particular user for the three month window ending today. To further complicate things, I want that dataset serialized in JSON format so that I have output like this:
{
"timestamp_1": count_1,
"timestamp_2": count_2,
...
"timestamp_n": count_n
}
So far I have arrived at a query that'll look something like this:
# Assume we have a user object called "user"
Deal.objects.filter(Q(sender=user) | Q(recipient=user)).extra({'date_created' : "date(created_on)"}).values('date_created').annotate(created_count=Count('id'))
Still combing through the documentation, but does anyone have a better way to tackle this?

I don't think Django can handle this without RAW sqls. There's a great django third-party package, django-qsstats-magic which is designed to make repetitive tasks such as generating aggregate statistics of querysets over time easier. It supports postgresql, Mysql, and sqlite.
The code below solves you problem.
import qsstats
import datetime
Deal.objects.filter(Q(sender=user) | Q(recipient=user))
qss = qsstats.QuerySetStats(qs, date_field='date_created', aggregate=Count('id'))
three_month_ago = datetime.datetime.now() - datetime.timedelta(months=3)
qss.time_series(start=three_month_ago, interval='days')

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
)

i have to transfer cust data to book. any possible method ? let me know please

from.models import Book,Cust
Cust.objects.get(acc, no1)
Book.objects.create(ac="acc",no="no1")
INSERT INTO Book (ac, no) SELECT ac, no FROM Cust.
i have to convert to django orm query how to do ?
Let me insist on asking you to provide sensible information in your questions.
So you can get started have a look at two basic methods:
Access the data in the database where (I'm assuming) both tables are installed and run the INSERT query you are mentioning;
Or add a method in your django's models.py to either of your models such as:
................
class Book(models.Model):
.........................
def updateBook(self):
set = Cust.objects.all().values('ac','no')
for e in set:
self.create(ac = e.cust, no = e,no)

Django - Search matches with all objects - even if they don't actually match

This is the model that has to be searched:
class BlockQuote(models.Model):
debate = models.ForeignKey(Debate, related_name='quotes')
speaker = models.ForeignKey(Speaker, related_name='quotes')
text = models.TextField()
I have around a thousand instances on the database on my laptop (with around 50000 on the production server)
I am creating a 'manage.py' function that will search through the database and returns all 'BlockQuote' objects whose textfield contains the keyword.
I am doing this with the Django's (1.11) Postgres search options in order to use the 'rank' attribute, which sounds like something that would come in handy. I used the official Django fulltext-search documentation for the code below
Yet when I run this code, it matches with all objects, regardless if BlockQuote.text actually contains the queryfield.
def handle(self, *args, **options):
vector = SearchVector('text')
query = options['query'][0]
Search_Instance = Search_Instance.objects.create(query=query)
set = BlockQuote.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank')
for result in set:
match = QueryMatch.objects.create(quote=result, query=Search_Instance)
match.save()
Does anyone have an idea of what I am doing wrong?
I don't see you actually filtering ever.
BlockQuote.objects.annotate(...).filter(rank__gte=0.5)

How do you perform a filtered database lookup in views?

I'm working with a database in Django. I'm familiar with the Django database API but am wondering how to interact with the data base inside views.py. Here's the relevant model:
class SlotFilling(models.Model):
originator = models.CharField(max_length=20)
empty_slot = models.BooleanField(default=False)
I'm trying to write an If statment in my program to check if empty_slot is True for a given originator. I'm thinking I might be able to use filter() to accomplish this. Any experience with the most efficient way to implement this?
If you are looking to query for originator all empty slots you can do something as following
SlotFilling.objects.filter(empty_slot=True, originator='someoriginator')
#comment code
Assuming originator is unique
originator_slot = SlotFlling.objects.get(originator='originator')
slot_value = originator_slot.empty_slot
You can use filter instead if originator is not unique, which would list you back all rows for particular originator
originator_slots = SlotFlling.objects.filter(originator='originator')
for originator_slot in originator_slots:
print originator_slot.empty_slot
Also please check out retrieving objects in DB API documentation as saying that you are familiar with it would be big overstatement :)

GQL Queries - Retrieving specific data from query object

I'm building a database using Google Datastore. Here is my model...
class UserInfo(db.Model):
name = db.StringProperty(required = True)
password = db.StringProperty(required = True)
email = db.StringProperty(required = False)
...and below is my GQL Query. How would I go about retrieving the user's password and ID from the user_data object? I've gone through all the google documentation, find it hard to follow, and have spent ages trying various things I've read online but nothing has helped! I'm on Python 2.7.
user_data = db.GqlQuery('SELECT * FROM UserInfo WHERE name=:1', name_in)
user_info = user_data.get()
This is basic Python.
From the query, you get a UserInfo instance, which you have stored in the user_info variable. You can access the data of an instance via dot notation: user_info.password and user_info.email.
If this isn't clear, you really should do a basic Python tutorial before going any further.
You are almost there. Treat the query object like a class.
name = user_info.name
Documentation on queries here gives some examples
There are some python tips that might help you
dir(user_info)
help(user_info)
you can also print almost anything, like
print user_info[0]
print user_info[0].name
Setup logging for your app
Logging and python etc