How to clear Django's cached query after prefetch_related - django-orm

I'm rendering a list of items with their related reviews. I used prefetch_related so it won't issue a new query for each item's reviews.
items = Item.objects.all().prefetch_related('reviews')
Later, I add a review and try to re-calculate the average:
item = items[0]
Review.objects.create(item=item, score=5)
# recalculate average
reviews = item.reviews.all()
...
Oh no! This list of reviews doesn't include the one I just created. How can I clear this cache so the query can be performed fresh? Or should I be creating the review differently?

prefetch_related(None)
Source: https://docs.djangoproject.com/en/2.0/ref/models/querysets/

This is not the correct answer as he want to do it after querying.
The correct way is using :
_remove_prefetched_objects
In this case :
item.reviews._remove_prefetched_objects()

Related

Get the Number of items found by *AllBy* testing-library queries

I'm familiar with the assertion of expect(element).toHaveLength(number),
I want to test for a new row addition in a table,
I could just assert some specific item's text to be in the document,
But the situation brought me to think it could be beneficial to be able to get the number of items found by testing-library's findAllby* queries.
I looked in the testing-library docs for an answer but it seems there is no easy way to check how many items were found by findAllby*...
Any ideas and suggestions will be appreciated
You can assert on the length of findAllBy* request results like so :
const rows = await findAllByText('my searched text');
expect(rows).toHaveLength(2);
React-testing-library's *All* queries return arrays : https://testing-library.com/docs/queries/about#types-of-queries

How to avoid customer's order history being changed in MongoDB?

I have two collections
Customers
Products
I have a field called "orders" in each of my customer document and what this "orders" field does is that it stores a reference to the product Id which was ordered by a customer, now my question is since I'm referencing product Id and if I update the "title" of that product then it will also update in the customer's order history since I can't embed each order information since a customer may order thousands of products and it can hit 16mb mark in no time so what's the fix for this. Thanks.
Create an Orders Collection
Store ID of the user who made the order
Store ID of the product bought
I understand you are looking up the value of the product from the customer entity. You will always get the latest price if you are not storing the order/price historical transactions. Because your data model is designed this way to retrieve the latest price information.
My suggestion.
Orders place with product and price always need to be stored in history entity or like order lines and not allow any process to change it so that when you look up products that customers brought you can always get the historical price and price change of the product should not affect the previous order. Two options.
Store the order history in the current collection customers (or top say 50 order lines if you don't need all of history(write additional logic to handle this)
if "option1" is not feasible due to large no. of orders think of creating an order lines transaction table and refer order line for the product brought via DBref or lookup command.
Note: it would have helped if you have given no. of transactions in each collection currently and its expected rate of growth of documents in the collection QoQ.
You have orders and products. Orders are referencing products. Your problem is that the products get updated and now your orders reference the new product. The easiest way to combat this issue is to store full data in each order. Store all the key product-related information.
The advantage is that this kind of solution is extremely easy to visualize and implement. The disadvantage is that you have a lot of repetitive data since most of your products probably don't get updated.
If you store a product update history based on timestamps, then you could solve your problem. Products are identified now by 3 fields. The product ID, active start date and active end date. Or you could configure products in this way: product ID = product ID + "Version X" and store this version against each order.
If you use dates, then you will query for the product and find the product version that was active during the time period that the order occurred. If you use versions against the product, then you will simply query the database for the particular version of the product itself. I haven't used mongoDb so I'm not sure how you would achieve this in mongoDb exactly. Naively however, you can modify the product ID to include the version as well using # as a delimiter possibly.
The advantage of this solution is that you don't store too much of extra data. Considering that products won't be updated too often, I feel like this is the ideal solution to your problem

Microsoft Cognitive Services - Bing News Search API V5. So many misunderstanding

I'm working on an app that use the Bing news API. We are currently using the V2 but we want to update it to V5.
We have a problem with the TotalEstimatedMatches attribute. This count is updated radomly when we try to iterate with the offset.
Sometimes the data are not relevant. or when we try to sort the results by date, the dates are not well sorted.
Is there someone who did it ? I really need help.
Thank's !
You should only integrate the very 1st TotalEstimatedMatches return value and use that as a constant maximum-bound while you use the 'count' & 'offset' params to iterate through pages of the same query. I use python primarily so I will here.
If:
TotalEstimatedMatches == 250,000
in the response returned from the first 50 results of your query. Then if you wanted to get a massive list of ALL 250,000 links you would do something like:
# Assuming count==50 & offset==0
max_bound = 250000
results = []
while offset <= max_bound-50:
results.append(your_search_function(your_query, count, offset, **stuff))
offset += count
If you were to keep doing offset calculations using the new TotalEstimatedMatches attribute generated after each query, you'll start skipping pages.
As far as the date-ranges go, I'm less sure. I think I read they're adding better functionality there soon.

Search inside an intmap collection for a specific attribute (not using map index)

My question is (again) about OPA database high-level API.
I have the following data-model declared:
database click = #mongo
db /click/click : intmap(Scan.scan)
and here's the Scan.scan type:
type Scan.scan = {
user : int
qr : int
date : Date.date
}
My problem here is that I need to query the database for specifics "clicks" for a given "qr" attribute, but the fact that an intmap is used forces me to retrieve all the clicks, and then manually search in the entire list for a match with the given "qr" parameter.
What I'm doing actually is fetching all the clicks via /click/click and then applying a List.filter on it....but I have performance issues (and I have the feeling that I'm doing MongoDB's work)
So my question is quite simple:
Did I miss something with the OPA database high-level API, or do I necessarily need to do a data migration on my click collection as I can't retrieve the intmap Index value that isn't stored anywhere else.
I hope my question is clear enough.
Thanks for your replies.
What I usually do in this situation is build another index, e.g.
db /click/by_qr : intmap(Scan.scan)
or
db /click/by_qr : intmap(int) // int represents user id
Of course, this means you have to be careful to maintain the index. My understanding is that there will eventually be a better way to handle this, but right now you have to do it manually; I agree it's not a very nice solution.

Satchmo: Specify delivery date/shipping date for an order

I working on e-commerce website using Satchmo. However, there are few customization required for my store.
While ordering a product I should be able to specify a delivery date (shipping date).
There can be only 20 (max_num_delievries) deliveries possible per day for a product. If number of deliveries for a particular date for a particular product exceeds 'max_num_delievries', user should not be able to select that date while ordering the product.
Can someone please help in this and guide me how to achieve this using Satchmo?
Thanks in advance..
I would try something like this:
1) create a local app (eg. delivery_date) with a model like "DeliveryDate" or so. For example localsite/delivery_date/models.py:
class DeliveryDate(models.Model):
product = models.ForeignKey(Product)
date = models.DateField()
order = models.ManyToManyField(Order)
class Meta:
unique_together = ("product", "date")
2) the validation of the max 20 existing orders... mhh, good question, maybe the best would be, to do it on the form? Override the clean method and check if this delivery date is associated with 20 orders already... maybe something like localsite/delivery_date/forms.py
class DeliveryDateForm(forms.ModelForm):
class Meta:
model = DeliveryDate
def clean(self):
super(DeliveryDateForm, self).clean()
... check here the order_set count
... but maybe the form isn't the best place to do this.
You also probably want to hide and auto-set the initial values for product and order yourself, and the user only being supposed to select a date.
3) Regarding satchmo... I would use signals to react after a product has been added to the cart (there is a signal just for this case), and add a listener which redirects the user to a view where he can select the date for this product. Look at the example here with the signal "cart_add_view": http://www.facebook.com/note.php?note_id=101466134049
Maybe ajax would be a good option here. With a hidden container in your page... which shows up after adding a product to the cart (only if the product hasn't already a DeliveryDate associated to this order/product), and asking the user to select a date.
This whole stuff would be on the listener: check if the product needs a delivery date, and if yes, send an ajax response to pop-up the window, and put in the repsonse-context the form, with the initial product and order hidden fields.
And to save the delivery-date you will need another ajax-view.
Well it's merely an idea how I would try to do it ;-) It will probably need adjustments here and there, of course. But hopefully it helps you further.
Regards,
Andrea