Can I access a specific field value from an object through accessing by the related name, in Django? - django-rest-framework

I'm making a vote app (Django rest framework), where users can post content and have it voted on through two options. The Vote modelVote model code has a ForeignKey field to the Post model, with the related name attribute "votes". The vote model also has a field named 'option', where choices 'option1' and 'option2' can be selected.
My goal is to count the total number of votes on a post, number of option1 votes and number of option2 votes.
I've been able to count the number of votes on a post through:
queryset = Post.objects.annotate(
votes_count=Count('votes', distinct=True),
)
Post views
I am unsure how to count the number of option1 and option2 votes, separately.

Related

How to add filter on item collection to get the Sales rep(total Quantity and Total no of Orders) of those Sale Managers which are logged in

$collection = $this->_itemCollectionFactory->create()->getCollection();
$collection->getSelect()->columns(array('total_orders' => new \Zend_Db_Expr('COUNT(order_id)')))
->columns(array('total_qty' => new \Zend_Db_Expr('ROUND(SUM(qty_ordered))')))
->group('sku');
$collection->getSelect()->limit(3);
$collection->addFieldToFilter('store_id', 2);
Through this code i can get the total quantity and total number of orders of all sales rep. But i need only those total quantity and total orders which were done by the Sales Rep og Logged in Sale Manager.
As you mentioned in your question you only want to get the order info based on a certain sales rep. To do that you need to somehow find a unique identify for the currently logged in sales rep and add a filter for that .
For example:
$collection = $this->_itemCollectionFactory->create()->getCollection();
$collection->getSelect()->columns(array('total_orders' => new \Zend_Db_Expr('COUNT(order_id)')))
->columns(array('total_qty' => new \Zend_Db_Expr('ROUND(SUM(qty_ordered))')))
->group('sku');
$collection->getSelect()->limit(3);
$collection->addFieldToFilter('store_id', 2);
$collection->addFieldToFilter('sales_rep_identifier', $loggedInSalesRepIdentifier);
The label sales_rep_identifier and the value $loggedInSalesRepIdentifier are just examples, you may have to adjust the format in which the data is stored if it doesn't currently have a field to check natively what sales rep did it, and adjust the values there accordingly
If you're using some kind of prebuilt system then maybe there are other labels for the identifier you could use, without more information on the specific database structure it's impossible to answer exactly, but essentially you need to filter by the unique sales rep identifier, and if that doesn't exist now in the database it should somehow but added

Validation list with multiple criterias

I sort out my problem but I am wondering if an easier way doing it doesn't exist.
With the function onEdit(), I am creating from a first validation list, a second validation list in the next cell.
So, the code below is just for information.
var validationRange = data.getRange(3, myIndex, data.getLastRow());
var validationRule = SpreadsheetApp.newDataValidation().requireValueInRange(validationRange).build();
activeCell.offset(0, 1).setDataValidation(validationRule);
In this validation list, I need to select a name, taking into account two additionnal criterias :
Name
Times
LastWeek
Patrick
2
W22
Rachel
5
W15
Claire
3
W14
Olivier
4
W16
Hélene
2
W20
It means that "Patrick" attended "2" times and last time was in week "W22".
I need to take into account these two criterias to select one of the attendee
I.E. : I try to let each person participate the same number of times but not every week (the oldest first)
So, I created a validation list with a "sorted key" that allows me to first see the person who has attended less and for longer.
Key Sorted
#02W20#Hélene
#02W22#Patrick
#03W14#Claire
#04W16#Olivier
#05W15#Rachel
This validation list is used 3, 5, 7 times in the same sheet because person can do different activities. Then, when all person are selected another script removes the values between # to keep only the name in the final sheet.
So, the question is :
could we create a validation list with multiple columns, the selected value being only the value of the first column.
I guess many users would enjoy it when we glance at questions about multiple criteras selection lists.
Thanks

Convert column value from null to value of similar row with similar values

sorry for the slightly strange Title I couldn't think of a succinct way to describe my problem.
I have a set of data that is created by one person, the data is structured as follows
ClientID ShortName WarehouseZone RevenueStream Name Budget Period
This data is manually inputted, but as there are many Clients and Many RevenueStreams only lines where budget != 0 have been included.
This needs to connect to another data set to generate revenue and there are times when revenue exists, but no budget exists.
For this reason I have gathered all customers and cross joined them to all codes and then appended these values into the main query, however as warehousezone is mnaually inputted there are a lot of entries where WarehouseZone is null.
This will always be the same for every instance of the customer.
Now after my convuluted explanation there's my question, how can I
-Psuedo Code that I hope makes sense.
SET WarehouseZone = WarehouseZone WHERE ClientID = ClientID AND
WarehouseZone != NULL
Are you sure that a client has one WarehouseZone? otherwise you need a aggregation.
Let's check, you can add a custom column that will return a record like this:
Table.Max(
Table.SelectColumns(
Table.SelectRows(#"Last Step" ,
each [ClientID] = _[ClientID])
, "Warehousezone")
,"Warehousezone"
)
This may create a new column that will bring the max warehousezone of a clientid everytime. At the end you can expand the record to get the value.
P/D The calculation is not so good for performance

rasa-core Map entities to other entites

I am building a simple food ordering bot. In this I have a take_order intent in which two entities will be extracted food_item and quantity, both of these entities have list types in slots, for example if a user message like this comes:
I would like to have [one] (quantity) [chicken burger] (food_item) and [two] (quantity) [fries] (food_item)
slot for this example will be: slot{“quantity”: [“one”, “two”], “food_item”: [“chicken burger”, “fries”]}
in the action user_take_order I will be multiplying quantity of each item to its price and giving total bill to the user.
But I have a problem, in a complex case when user do not provide a quantity for the food_item, I will be assuming the default quantity to one but the problem occurs when user orders three items and do not provide quantity for only the second item, for example:
I would like to have [one] (quantity) [chicken burger] (food_item), [fries] (food_item) and [two] (quantity) [soft drinks] (food_item)
in this example no quantity is provided for the fries and slots filled: slot{“quantity”: [“one”, “two”], “food_item”: [“chicken burger”, “fries”, “cold drink”]}
in the action user_take_order I would like to do this:
1 x price_of_chicken_burger
1 x price_of_fries
2 x price_of_cold_drink
but the problem is that in quantity slot I have only quantities of chicken burger and cold drink and I do not have a clue that user did not mention the quantity of fries( I want to set quantity of fries as 1 “default case”)
have I choose the wrong types for slots quantity and food_item?
slots:
food_item:
type: list
quantity:
type: list
One of the possible solutions is to extract quantity and food item as one entity:
I would like to have [one chicken burger] (quantity_food_item), [fries] (quantity_food_item) and [two soft drinks] (quantity_food_item)
then differentiate them inside an action.

Laravel Eloquent - Sum of a column values for multiple records from related data

I have the following models: User, Order, OrderPayment
whereby each user has many orders, and each order has many order payments.
The orderPayment model has the attribute "total_paid"
I would like to get the sum of the user's total paid for all his orders.
eg:
user has 3 orders.
the first order has the two following payment records: 5$ and 4$.
the second order has one payment of 10$
the third order has two payment records of 1$ and 4$
the total sum i want is 5 + 4+ 10+ 1+ 4 = 24$.
I have tried the following but it's not working at all :
$user->orders->orderpayment->sum('total_paid');
but i get this error
Property [orderPayment] does not exist on this collection instance
Since you want to sum values from the OrderPayment model, it is easier to start there. Try to write it like this:
OrderPayment::whereHas('order.user', function($query) use ($userId) {
$query->whereId($userId);
})->sum('total_paid');
Make sure all the relations are defined well.
Try:
$user->orders->orderpayment()->sum('total_paid');

Resources