Django insert or update in one table should reflect in another table - django

I am trying to create a cart using django-carton App. I have two models: Halls and Caterer. I want to add either of these Halls or Caterer object in cart when I will call add() method. While using this API, I need to register my model in settings.py as below
CART_PRODUCT_MODEL = 'marriage_halls.models.Hall'
I can register only one model at a time. So I can't add Caterer object in the cart.To resolve this issue, I'm planning to create new 'product' model which will contain 3 columns viz. {name, price, city}. These are the columns which are common in both Hall and Caterer and I want to display them when I'll call show() method. My first question is, is it a correct way to do it?
If its a correct approach, What I want to do is, whenever I will add new Hall or Caterer in their respective tables through Django's admin interface, only these 3 column values should get inserted to Product table (INSERT new row in product table).
How can I achieve this?

Make Product a base class and use multi table inheritance.
https://docs.djangoproject.com/en/1.10/topics/db/models/#multi-table-inheritance

Related

How to populate table based on the condition of another table's column value in Django

I am kinda new in django and I am stuck.
I am building and app to store equipment registry. I have done a model for equipment list and i have a status values as "available", "booked", "maintenance"
I also have a model for all equipment that are not available. not in my html in the "not available registry" i want to show only details of equipment in the list that are marked as "booked" and "maintenance"
There are three ways of doing this.
To filter out objects of the model that are marked as "booked" or "maintenance" you can use complex lookups with Q objects. It allows you to filter objects with OR statement. Here you need to find objects that have status set to "booked" OR to "maintenance". The query should look like this:
from django.db.models import Q
Equipment.objects.filter(Q(status='booked') | Q(status='maintetnance'))
Second way of doing this is by using __in statement to filter objects that you need:
not_available_status = ['booked', 'maintenance']
Equipment.objects.filter(status__in=not_available_status)
And final way is to exclude objects that you don't need:
Equipment.objects.exclude(status='available')

Join two records from same model in django queryset

Been searching the web for a couple hours now looking for a solution but nothing quite fits what I am looking for.
I have one model (simplified):
class SimpleModel(Model):
name = CharField('Name', unique=True)
date = DateField()
amount = FloatField()
I have two dates; date_one and date_two.
I would like a single queryset with a row for each name in the Model, with each row showing:
{'name': name, 'date_one': date_one, 'date_two': date_two, 'amount_one': amount_one, 'amount_two': amount_two, 'change': amount_two - amount_one}
Reason being I would like to be able to find the rank of amount_one, amount_two, and change, using sort or filters on that single queryset.
I know I could create a list of dictionaries from two separate querysets then sort on that and get the ranks from the index values ...
but perhaps nievely I feel like there should be a DB solution using one queryset that would be faster.
union seemed promising but you cannot perform some simple operations like filter after that
I think I could perhaps split name into its own Model and generate queryset with related fields, but I'd prefer not to change the schema at this stage. Also, I only have access to sqlite.
appreciate any help!
Your current model forces you to have ONE name associated with ONE date and ONE amount. Because name is unique=True, you literally cannot have two dates associated with the same name
So if you want to be able to have several dates/amounts associated with a name, there are several ways to proceed
Idea 1: If there will only be 2 dates and 2 amounts, simply add a second date field and a second amount field
Idea 2: If there can be an infinite number of days and amounts, you'll have to change your model to reflect it, by having :
A model for your names
A model for your days and amounts, with a foreign key to your names
Idea 3: You could keep the same model and simply remove the unique constraint, but that's a recipe for mistakes
Based on your choice, you'll then have several ways of querying what you need. It depends on your final model structure. The best way to go would be to create custom model methods that query the 2 dates/amount, format an array and return it

Change one django form field value relative to another

Let say I have two fields in a django form country and state.I want the values of state to relatively change with the values of country.i.e. I want the state field to list out the states of the country that user has selected. Also the state field should be empty during form initiation.I know that this can be done using java script and other scripts.But,I would like to know if there are any conventional methods exists in django to do the same.???
Sounds like you need to create a model for Country and State.
State model should have a foreign key linking to Country. This means many states can be related to one country. Then, populate the tables with all countries and states you want.
In your form, you can override the 'init' method with custom behavior. So, if you have declared a field 'state' then you can do something like self.fields['state'].choices = State.object.filter(country_id=some_country_id). This assumes you have some_country_id already and you can pass this through as a kwarg during instantiation.

How to interact with Existing database with Model through template function in Django

I have an existing table called empname in my postgres database
(Projectid,empid,name,Location) as
(1,101,Raj,India),
(2,201,David,USA)
So in the app console it will have like the following
1)Projectid=Textbox
2)Ops =(view,insert,Edit)-Dropdown
Case1:
So if i write project id as 1 and select View Result:It will display all the records for Projectid =1(Here 1 record)
Case2:
If i write projectid as 3 and select insert it will ask for all the inputs like empid,name,address and based on that it will update the table .
Case3:
If i write projectid as 2 and select edit.Then it will show all the field for that id and user can edit any column and can save which will update the records in backend for the existing table
If there is not data found for the respective project id then it will display no records found
Please help me on this as I am stuck up with models
Once you have your models created, the next task should be the form models. I can identify atleast 3 form classes that you will need to create. One to display the information(case 1), another to collect information(case 2) and the last class to edit the information. Wire up the form to the views and add the urls.
A good reference could be a django a user registration form since it will have all the three cases taken care of.http://www.tangowithdjango.com/book17/chapters/login.html

How to join non-relational models in Django 1.3 on 2 fields

I've got 2 existing models that I need to join that are non-relational (no foreign keys). These were written by other developers are cannot be modified by me.
Here's a quick description of them:
Model Process
Field filename
Field path
Field somethingelse
Field bar
Model Service
Field filename
Field path
Field servicename
Field foo
I need to join all instances of these two models on the filename and path columns. I've got existing filters I have to apply to each of them before this join occurs.
Example:
A = Process.objects.filter(somethingelse=231)
B = Service.objects.filter(foo='abc')
result = A.filter(filename=B.filename,path=B.path)
This sucks, but your best bet is to iterate all models of one type, and issue queries to get your joined models for the other type.
The other alternative is to run a raw SQL query to perform these joins, and retrieve the IDs for each model object, and then retrieve each joined pair based on that. More efficient at run time, but it will need to be manually maintained if your schema evolves.