When to use an abstract model? - python

There's a form on our website that gives you a quote if you enter a to and from address. From there, you can go ahead and make a booking or just leave the website. We save the quotes generated by users for statistic purposes (e.g compare the quote and booking ratio). Currently, I use two tables for this. Quotation and Booking. Here are the tables (models in Django):
Quotation:
to
from
price
some_charge
other_charge
Booking:
to
from
price
some_charge
other_charge
name
# other booking details
I have kept them as separate models but I have noticed they are getting very similar over time. I am adding fields to both models and also have duplicate methods. Should I make a QuotationModel and extend both from that? Any other suggestions? Any theory I should for a scenario like this?

Related

Django: Get each user Invoices, Expenses, Withdrawals. (ORM) relationship

I've been stuck for a couple of hours, and can't figure out the correct way to do it. So basically I know that looping is not a really good practice, because if we would have a lot of users, the system would start time outing. So my idea is to pick the correct way to get the things that I need.
This is our core scheme:
I need to make this kind of 'table', and these are the things that I need:
This is the thing that will be displayed in our Front-End, so for now, I only need to collect the correct data and pass it into our FE. We use celery tasks, so the timing is always set (Mondays at 6 PM for ex.)
This is what I've tried so far..
for user in User.objects.all():
start_date = timezone.now() - timedelta(weeks=1)
# How to loop correctly over every user and check for invoices??
invoices = InvoiceItem.objects.select_related('invoice', 'invoice__operation_ptr_id')
# invoices[0].operation_ptr_id ???
The looping for user in User.objects.all() should probably be replaced to annotate. How can I make the relationship to get invoices, withdrawals, expenses?
Try querying from the User instead of InvoiceItem models
I'm not sure what specifically you need to return to the frontend, but if needed, returning the actual values should be quite easy after doing some annotations
To get the number of invoices of a user try this:
from django.db.models import Count
User.objects.annotate(total_invoices=Count("invoices"))
As for withdrawals and expenses, it seems like those models don't have a relationship with the User model at all. I would suggest updating your models to add a relationship between them, and query them similarly like the query above.
I'm also making the assumption that User = Customer, since you didn't actually provide the Customer model in your other post.

How to provide different sets of data to different users in django?

I'm a newbie to the django framework and trying to make a watchlist for stocks. I've already made the crux of the webapp, where-in, a user can search for a quote and add it to their watchlist, along with relevant data about that quote.
What I want to do now is, to save the separate watchlists that different users are creating (after creating an account on my site) and upon logging in to my site, they can view their personalized watchlist and edit it.
I'm using a model for storing the data for the watchlist quotes and looking for a way to provide the different personalized watchlists depending upon the logged in user.
Can anyone give me a lead on how to employ the logic for this? Do I need to use two data bases - one for the data of the users and the other one for storing the respective user watchlists? If yes, how do I connect everything?
EDIT: Ever used a stock investment app? The way every user/customer can log in to their account and make/edit and save their watchlists in the app - that is the functionality I want to implement. How/Where do I store so many watchlists?
use 'request.user' from your view, to know the user who sent the request and return the corresponding watchlist

Create portfolio backed skill-set in django ORM

I have a specialized User class that inherits from django.contrib.auth.models.User. Now, this User class will have tags associated with it, for example: Blogger, French Cuisine Cook, Python Programmer.
Ideally, what I want to do, is have each of these traits backed up by something that they have done, ideally a PortfolioItem. So, a User will have a set of tags, and these tags, and the relationship with each of these tags is going to be understood through these PortfolioItems. How would one achieve something like this using the django ORM?
Please note, that the tags are generic, however, the portfolios behind each of these tags are unique to every user.
How would one go about doing, this using the through variable in django ORMs.
UPDATE
I've tried simple adding PortfolioItem as the through variable, but in that case you will need to create a unique tag each time you want to add a list of portfolio item. The thing is I want tags to be generic.

django model add category to object

class Venues(models.Model):
..........
..........
category=models.ForeignKey(Category)
class Category(models.Model):
club=models.CharField()
bar=models.CharField()
adult=models.CharField()
These are the models that I have. I am a django newbie so please pardon this rather simple question. I want every Venue object to have one category that is selected from the list of categories(i.e club,bar or adult). So each category--club,bar,adult--can have many Venues but like I said every Venue has one category.
So am i at all close to what im trying to accomplish or is this totally wrong?? Please help. Thanks
Your Category could have a one field called type that type could be a string either 'club', 'bar', 'adult'. Also you could just have a Venue with a char field and give it a set of fixed choices. So as you see there are already a couple of ways to approach the way you set up your database. Can venues have more than one category? If so you might want to use a manytomany field.
I think one of the issues is right now if you wanted to add a new category you would have to manually add it in the code. If you chose a gave Category just a type field a user could add new categories from the admin without changing any code.
if you're wondering how to actually add a category to a Venue you first need to get a category instance. This can be done by retrieving one already in your db or createing a new one
category = Category.objects.get(pk=1)
next you can just create a new Venue using that category
new_venue = Venue(category=category, other_args)
new_venue.save()
will save a new venue with the category. Django documentation provides a great reference.

Return template as string - Django

I'm still not sure this is the correct way to go about this, maybe not, but I'll ask anyway. I'd like to re-write wordpress (justification: because I can) albeit more simply myself in Django and I'm looking to be able to configure elements in different ways on the page. So for example I might have:
Blog models
A site update message model
A latest comments model.
Now, for each page on the site I want the user to be able to choose the order of and any items that go on it. In my thought process, this would work something like:
class Page(models.Model)
Slug = models.CharField(max_length=100)
class PageItem(models.Model)
Page = models.ForeignKey(Page)
ItemType = models.CharField(max_length=100) # tells me which model to display
InstanceNum = models.IntegerField() # tells me which instance of which model...
Then, ideally, my template would loop through all the PageItems in a page which is easy enough to do.
But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to pull different item types back in different orders and display them using the appropriate templates. Now, I thought one way to do this would be to, in views.py, to loop through all of the objects and call the appropriate view function, return a bit of html as a string and then pipe that into the resultant template.
My question is - is this the best way to go about doing things? If so, how do I do it? If not, which way should I be going? I'm pretty new to Django so I'm still learning what it can and can't do, so please bear with me. I've checked SO for dupes and don't think this has been asked before...
I've also looked at Django-cms to see if that helps, but I couldn't get to grips with it.
Any suggestions?
First, some puzzelement.
InstanceNum = models.IntegerField() # all models have primary keys.
In Django, all model are assigned an integer primary key.
The comment doesn't make sense, since you don't need to add a primary key like this. The PageItem already has a primary key.
Also, please use lower case letters for attributes. Only Use Upper Case for Class Names. Please.
"But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to
pull different item types back in
different orders and display them
using the appropriate templates"
Different types usually means different models. Rather than a vague "PageItem", you probably want to have "Site Update" and "Blog Post" as separate models.
You can then iterate through these various objects and display them in the template.
You can easily have your various Models defined with a method to return HTML information. You don't (generally) want to return fully-baked HTML. But CSS ID or Class information is sometimes helpful.
class SiteUpdate( models.Model ):
page = models.ForeignKey(Page)
item_text = models.CharField(max_length=100)
item_css_class = models.CharField(max_length=64)
Now you can generate this into the template with a simple <div class="{{item.item_css_class}}">{{item.item_text}}</div> and use CSS to handle the formatting details that distinguish site update as opposed to a blog post.
The include template tag can take a variable containing the template to include, so you could loop through a sequence containing the various sub-templates and include them in turn, maybe using a dict to map friendly names to template filenames.

Categories