How to effectively manage cache (Redis) with Django Rest Framework? - django

We have been working with Django and Django RestFramework for quite a time now and facing a lot of challenging to manage cache in Redis, our models look like
(1) School (Details of School)
(2) Teacher (FK School, with all details of teacher)
(3) Student (FK Teacher, with all details of Teacher)
Our users would be operating CRUD operation on School, like /get_all_info should return a JSON object like,
{
"name": "something"
"teachers": [
{
"name": "teacher1 name",
"students": [
{
"name" : "student1 name"
}, ... all students of that teacher
]
}, ... all teacher of that school
]
}
Also, the whole system is very dynamic, each component keeps on changing. Around 90% of requests are of the type stated above.
We were thinking of adding post-save signals to delete full cache each time for the school like a student is updated in post-save first we will find his-her school then delete cache for that school. Is there is some more elegant/better approach? Is there any python library that can handle all this?

Related

django: use model methods without create instance

I have a Model Product with business methods. My model contains relationship with Models Item and Dealer.
Let's say my Product is serialized as / can be created from:
{
"name": "productA",
"items": [2,3,13],
"dealer": [1,2]
}
I can for instance run Product.simulate():
class Product(Models):
....
def simulate(self):
```dummy function to illustrate```
return sum(i.price for i in self.items.all()) / len(i.dealer.all())
I would like to be able to compute Product.simulation with values in a dictionnary without creating Product instance. I have multiple signals and batch operation on Product Model I dont want to run on the only for simulation objects.
I could create a for_simulation attribute on Product and specify on my signals / batch operation to don't run on those instances but it seems do lead to duplicate code and be forgotten on some signals / batch.
On the other hand, I could rewrite all my methods in Product, Item, Dealer to work with dict as input but there's a lot of them.
Is there a better way to achieve my goal ? Ideally I would like to be able to do something like:
p = Product({
"name": "productA",
"items": [2,3,13],
"dealer": [1,2]
})
p.simulation()
I cannot: my instances need to be saved to build relationships.

Django id vs pk in fixtures/loaddata

A strange (to the uninitiated lol) issue with models using a custom CharField for a primary key/id:
id = models.CharField(max_length=10, primary_key=True)
Feeling I know what I'm doing, I've created the following (json) fixtures file:
[
{
"model": "products.product",
"id": "am11",
"fields": {
"title": "Test Product A",
}
},
{
"model": "products.product",
"id": "am22",
"fields": {
"title": "Test Product B",
}
}
]
, and proceeded with loading it:
✗ python manage.py loaddata fixtures/products.json
Installed 2 object(s) from 1 fixture(s)
Well, it kinda lied. A check on the admin page or in a shell shows that there's only one Product in the database - the last one in the fixture's list. Curiously enough, attempts to delete this Product via the admin page silently fail, only via the shell can it actually be deleted. Further investigation (in the shell) revealed an interesting problem - that (single) Product created has pk/id set to an empty string(?!..but explains why admin fails to delete it). If I manually create another, either on admin page or in the shell, the new product appears without any issues, both id and pk set to the string given. But loaddata with fixture fails on this. Originally discovered this problem when a basic test failed - given the same fixture, in failed the assertion on the number of products in the queryset, claiming there's just one.
Now, I was able to "fix" the problem by renaming 'id' to 'pk' in the fixture file. I say 'fix', because I don't understand what bit me here. Any clue will be appreciated. Thanks!

Using hasMany relation and cascading ORM level in loopback4

I have created 2 models Author and Books where Author has hasMany relation with Book and Book has belongsTo relation with author.
While saving data using ORM models the cascading is not happening i.e
{
"authorId": 1,
"name": "qwery",
"experience": 2,
"books": [{
"BookId": 12,
"category": "string"
}]
}
The above should create a Author record in Author table and create a Book record with the authorId in Book table, which is not happening whereas from belongsTo it can able to create an Author record with just authorId.
You can find the code in the following GIT
You need to create a AuthorBookController to connect the two. Please see example code in here: https://github.com/strongloop/loopback-next/blob/master/examples/todo-list/src/controllers/todo-list-todo.controller.ts

Backbone-relational with Django

I'm building a Backbonejs app that is running Django in the backend. In my Django, i have models like Author, books, shelf and user and they are related to one another. In Backbone, I have a model Author and when I do a fetch() I get its related models in an array. Should I proceed like this or it's better to create the same models in Backbone and do the same relations between them? (with backbone-relational)
Also, let's say I go with the second option, when i do fetch() and get related models, shall backbone-relational recognize it directly?
Thanks
I would recommend leveraging Backbone relational--especially if you expect the app to get somewhat complex later.
Probably you won't have to change your server side code, you can get Backbone relational to instantiate any related models that are included in the JSON of the model you have fetched. So if for an author query your backend returns:
[{
name: "Hemingway, Ernest",
books: [
{name: "For whom the bell tolls", ISBN: 1234},
{name: "The sun also rises", ISBN: 2345}
]
}]
... and you have defined a has-many relationship between Authors and books Backbone relational will instantiate the books as well.

Group models in django admin

Is there any way to group the models in django admin interface?
I currently have an app called requests with the following models showing in the admin site:
**Requests**
Divisions
Hardware Requests
Hardware Types
Requests
Software Requests
Software Types
I would like the divisions, Software Requests and Hardware Requests to be grouped separately in a "Types" group.
I know I could override and hard code the admin/index.html and base_site.html but this seems rather convoluted just to specify grouping.
Is there anything i can add to the Meta class to specify a group name?
The only way I have found so far to achieve what i want is to move the models to a new app within requests ("requests.Types") but again, doesn't feel like its the 'correct way'.
You can do it using django-modeladmin-reorder.
You'd configure it somehow along these lines then (settings.py):
ADMIN_REORDER = (
{'app': 'requests', 'label': 'Types',
'models': (
'requests.Divisions',
'requests.HardwareRequests',
'requests.HardwareTypes'
)
},
{'app': 'requests', 'label': 'Other models',
'models': (
'requests.Requests',
'requests.SoftwareRequests',
'requests.SoftwareTypes'
)
},
)
There isn't anything you can put in the model definition to do this, because models -- by design -- don't know about the existence of the admin, or how they'll be presented in the admin.
This really is a case where you just write a template that does what you want, and use it; all you're asking for is a presentational change, and templates are where you do presentation in Django.