Single model instances on separate html - django

What is a best way to display single model instances on different html? I know how it is done on single page (forloop), but could not figure out how the same would be possible on different html. i.e. single question per page?
my pseudo model:
class Question(models.Model):
desc = models.CharField()

Related

Caching list of id's of django queryset, and reusing that list for another Viewset

Let's use these 4 simple models for example. A city can have multiple shops, and a shop can have multiple products, and a product can have multiple images.
models.py
class City(models.Model):
name=models.CharField(max_length=300)
class Shop(models.Model):
name = models.CharField(max_length=300)
city = models.ForeignKey(City, related_name='related_city', on_delete=models.CASCADE)
class Product(models.Model):
name=models.CharField(max_length=300)
description=models.CharField(max_length=5000)
shop=models.ForeignKey(Shop, related_name='related_shop', on_delete=models.CASCADE)
class Image(models.Model):
image=models.ImageField(null=True)
product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE)
For an eCommerce website, users will be writing keywords and I filter on the products names, to get the matching results. I also want to fetch together the related data of shops, cities and images, relevant to the products I will be showing.
To achieve that I am using .select_related() to retrieve the other objects from the foreignKeys as well.
Now, my question is, what is the best way to send that to the client?
One way is to make a single serializer, that groups all data from all 4 tables in a single JSON. That JSON will look like 1NF, since it will have many repetitions, for example, there will be new row for every image, and every shop that the product can be found, and the 10.000 character long description will be repeated for each row, so this is not such a good idea. More specifically the fields are: (product_id, product_name, product_description, product_image_filepath, product_in_shop_id, shop_in_city_id)
The second approach will use Django queryset caching, which I have no experience at all, and maybe you can give me advice on how to make it efficient.
The second way would be to get Product.objects.filter(by input keywords).select_related().all(), cache this list of id's of products, and return this queryset of the viewset.
Then, from the client's side, I make another GET request, just for the images, and I don't know how to reuse the list of id's of products, that I queried earlier, in the previous viewset / queryset.
How do I fetch only the images that I need, for products that matched the user input keywords, such that I don't need to query the id's of products again?
How will the code look like exactly, for caching this in one viewset, and reusing it again in another viewset?
Then I also need one more GET request to get the list of shops and cities, where the product is available, so it will be fantastic if I can reuse the list of id's I got from the first queryset to fetch the products.
Is the second approach a good idea? If yes, how to implement it exactly?
Or should I stick with the first approach, which I am sceptical is the right way to do this.
I am using PostgreSQL database, and I will probably end up using ElasticSearch for my search engine, to quickly find the matching keywords.

How to save a model record as a template for reuse later

I have a basic blog app that has a Post model:
class Post(models.Model):
author = models.ForeignKey(
get_user_model(), null=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=30)
content = models.CharField(max_length=30)
template_specific_entry = models.CharField(max_length=30)
I need users to be able to create a Post template with template_specific_entry field values, and then other users to use these templates to create new post records, updating title and content but not template_specific_entry.
See the example use case below:
I would like to retain the original Post templates in their original form, so multiple versions of that template can be used.
My question is: what's the most efficient way to go about creating this structure?
Should I create two models, PostTemplate and Post and somehow link the template_specific_values between them?
Since this is 'row level' functionality, is it better to do this via model methods, so templates and posts are stored in the same model? E.g. def createTemplate(self): and def createPost(self): referencing the same model?
In each case how would I actually implement this?
Your drawing is a very good way to understand the problem you're trying to solve. And in fact, it's also clearly showing how your models should be constructed. You have templates and posts and each post needs to be linked to one and only one template.
You can almost see your drawing as the blueprint for your models:
PostTemplate has a ForeignKey to User (since there's an author, in your example "Author1") and has some specific characteristics (template_specific_values although I would try to name this field differently). Note that you use plural here, so I'm wondering if this should be a CharField and not something else, like an ArrayField.
Post has a ForeignKey to User (the author) and to PostTemplate, so that one template can "have" many posts, but each posts only one template.
When the user has selected a template, and then writes the post, the fk of the post gets set to the chosen template.

django-rest-framework multiple serializers in the same request

I know there's something similar answered here, but my question is not the same. I'm using multi-table inheritance to model 2 different types of entities, and both of them can create posts. My problem is when trying to create a view that shows all the posts together.
So I have my Entity model, and then my ETypeA and ETypeB models, which look like this:
class Entity(models.Model):
pass
class ETypeA(Entity):
# Here are some attributes
pass
class ETypeB(Entity):
# Here are some attributes
pass
As you can see, the Entity model it's just for having a common primary key between ETypeA and ETypeB. The reason for this is to have just one common Post model, like this:
class Post(models.Model):
transmitter = models.ForeignKey(Entity, on_delete=models.CASCADE)
text = models.CharField(max_length=500, null=False, blank=False)
The problem now is that when I create a view to show the posts I get only the id of the transmitter but I need the whole information. The way of doing it in SQL should be joining the results with ETypeA, then with ETypeB and make a union between the results (keeping some fields as nulls). Then I should be capable of sorting them by date. How can I do that with DRF views and serializers?

django - query mutliple models for the same field in each in 1 query

Say I have 3 models (Blog, News, Photos) and i want to get the latest 3 pieces of content regardless of which model they belong to.
With (psuedo) sql I could do something like:
SELECT *
FROM blog, news, photo,
WHERE is_published=True
ORDER by publication_date
LIMIT 3
I don't really want to use to use raw sql in Django as i want a query set returned, so is there a way I can make this type of query with Django?
Thanks,
If the 3 models are similar in some way (as they appear to be), the way I would probably do it is by creating a base model and then have the 3 other models inherit from that model.
class Publishable(models.Model):
is_published = models.BooleanField(default=False)
publication_date = models.DatetimeField()
... other fields ...
class Blog(Publishable):
...extra fields...
class News(Publishable):
...extra fields...
class Photos(Publishable):
...extra fields...
Then later on, you can do:
Publishable.objects.order_by('-publication_date')[:3]
If you still need the "type" associated with the retrieved models, check out the Inheritance Manager
You'll probably want to read about the pros and cons about Model Inheritance as well.

Non-model field in Django model

I would like to have a model in Django that has multiple pictures associated with it. I'm evaluating possible options.
One picture for one model is easily done with the models.ImageField(...).
However, I would like a array (or set) of pictures. It can be just paths, not necessarily ImageField objects.
The problem is, how do I create that field in a Django model? I am assuming I will need to create a field that is not part of models.WhateverField. Is that possible? Can I define a non-model field, such as:
class MyModel:
name = models.CharField(max_length=10)
picture_list = []
and then do:
def sample_add_picture_view(request):
picture = "sample.jpg"
model = MyModel.objects.get(id=sample_id)
model.picture_list.append(picture)
model.save()
return HttpResponseRedirect('index.html')
Could this be done? If not, what could be a better solution? Thank you !
You need to create two separate models and link them with a ForeignKey field, like so:
class Item(models.Model):
name = models.CharField(max_length=255)
class ItemImage(models.Model):
image = models.ImageField(upload_to="item_images")
item = models.ForeignKey('Item', related_name="images")
It is possible to make a custom field to store multiple items, but it's a really bad idea. You would have to serialise an array into the database, making maintenance very difficult. Using a separate model means you can store extra information such as upload times, image captions etc with little extra effort.