Can I create a calculated column that totals the record count in another list based on a field value?
Example:
List1 contains departments, each with a deptID
List2 contains employees, each assigned to a deptID
Can List1 contain a total employee count (for that deptID)?
No, this field does not exist.
You can create custom view or workflow (or maybe eventreciever) on add item in the list2, which will change corresponding field of conformity item in the list1.
But it's best just to create the custom view.
No, calculated field can refer only to fields in the same item.
I suggest you to use EventReceiver to accomplish your request. Register the receiver to the employee list with ItemAdded, ItemUpdated and ItemDeleting events. In the receiver's methods update corresponding department item and its field (number of employees).
Related
When I try to save a new item I need to find the item with the highest ID in the database in order to add 1 to it and save the next item in the order in the database. Simply counting the items in the DB will not work as if an item is deleted the count will be incorrect.
I have no code to fix but pseudo looks something like:
look at all the items in the DB
Find the item with the highest ID
Add one to that number
save the new item with the new highest id in the DB
I am using Django. as such it should use the querysets within Django and or python.
Field id of the Django Model is by default auto increment so whenever you save a new object to the database it does exactly what you want - saves object with id greater than the last object's id by one.
Anyways, there are multiple ways you can retrieve latest id from the database.
The most efficient way (simplest and fastest database query since you want only id value returned, not the whole object) is by saying:
latest_id = Model.objects.all().values_list('id', flat=True).order_by('-id').first()
The queryset looks like this:
SELECT 'model'.'id' FROM 'model' ORDER BY 'model'.'id' DESC LIMIT 1;
all() gets all objects of the model from the database, values_list('id', flat=True) extracts only the value of the id field (this saves you time because you don't retrieve all model fields), order_by('-id') orders objects by id in descending order and first() gives you the desired result which is the last id.
There is also method like last() that does the oposite of method first(). It retrieves last whole object of the model from the database or the method latest('id') which does the same.
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
I have a table which has a list of invoices and their details:
class Invoice(models.Model):
invoiceNum = models.CharField(etc...)
invoiceDate = models.DateField(etc...)
customerID = models.ForeignKey(etc...)
isPaid = models.CharField(etc...)
The Invoice records do not hold the actual invoice total. Instead, an invoice's total is made up of several Invoice_Line_Item records, held in another table:
class Invoice_Line_Item(models.Model):
invNum = models.ForeignKey(Invoice)
itemName = models.CharField(etc...)
itemPrice = models.DecimalField(etc...)
I have a webapp that shows all the invoices in a big HTML table, along with all the details of that invoice on the table's tr row. Details such as, Invoice Date, Invoice Number, Customer ID, all come from that Invoice table. There are hundreds of invoices to display in this HTML table.
What I would like to do is also show each invoice's total value - which is the sum of all the line items. However, I can't think of a simple way to acomplish this since the invoice details and the line items that make up the invoice's total are in two different tables.
One way I thought is to pass the entire Invoice_Line_Item querySet into the HTML template, then for each invoice displayed in a table tr, I could iterate over the entire Invoice_Line_Item querySet, adding up all the line items that match the current invoice. This, however, seems hugely inefficient.
Any better ideas on how to do this?
Thanks!
One word: Aggregation
Invoice_Line_Item.objects.filter(invNum=invoice).aggregate(Sum('itemPrice'))
https://docs.djangoproject.com/en/dev/topics/db/aggregation/
Another way is to store the total in Invoice and update it whenever you change a related Invoice_Line_Item
One more word: annotate.
from django.models import Sum
Invoice.objects.filter( .. ).annotate( InvTotal=Sum( 'invoice_line_number__itemPrice' ) )
InvTolal becomes a new attribute of Invoice object, you can use it in template the same way as invoiceNum or invoiceDate.
With this approach you do not have to pass any additional data structures to your template, only a QuerySet of Invoices.
Please note:
Argument of Sum is a string, which is a concatenation of the name of related model converted to lowercase, than double '_', and than the name of a field in related model.
The description below is heavily simplified - it's only one part of a bigger problem that we are tackling but the innards can be safely left out for this question.
Suppose we have the following models: -
class Item(models.Model):
name = models.CharField(max_length=150)
value = models.DecimalField(max_digits=12,decimal_places=2)
class Person(models.Model):
name = models.CharField(max_length=150)
items = models.ManyToManyField(Item, through='AssignedItem')
class AssignedItem(models.Model):
person = models.ForeignKey(Person)
item = models.ForeignKey(Item)
value = models.DecimalField(max_digits=12,decimal_places=2)
So basically a person may be assigned zero, one, or more items and each assigned item's value may be overridden for a particular person by specifying the new value in the through model.
What we are aiming to achieve is an html table which has all the Item.name as its header row, with one extra column in that header row for Person.name.
Each Person may have a different set of Person.items assigned to them so it is expected that if a Person has not been assigned an Item, the corresponding cell for that Person will be blank (please see attached image).
The question is how to place the correct AssignedItem value in the corresponding column. We have a Queryset of Items that we are looping over in the template to create the header row, and then we have a list of lists containing each person's items. But how do we ensure that the correct AssignedItem is displayed under the corresponding Item header?
You mentioned you are constructing the list in the view,
We have a Queryset of Items that we
are looping over in the template to
create the header row, and then we
have a list of lists containing each
person's items.
When constructing this list, make the list an ordered list, where if a particular value exists, assign it and if it doesnt, then insert None.
ie, the list for Jake should look like [78, 45, None, 94, 72]
Edit:
Since reordering is an issue, use a dictionary with the item as index
ie, the values for Jake should look like {'Item1':78, 'Item2':45, 'Item4':94, 'Item5':72}
Well, the main issue was to ensure that the correct AssignedItem is displayed under the corresponding Item header.
I tried a lot of things in the template, but it did not offer too much room to maneuver. I ultimately created the "table" in the view then passed the string to the template for rendering.
I want to insert the product in the product table but the product table is also having a category Id which is the foreign key ,How will I insert the foreign key through code please tell me.
i have used this syntax
NewItemToInsert.tbl_PRODUCT_CATEGORY.category_id = Convert.ToInt32 (categoryId);
Categories are displayed in the dropdown list on the add product page and to bind that dropdown I have written a class.
Category Id which I want to insert already exists in the Category table and that Id I want to add into Product table
Please give me useful suggesstions
Thanks
Ritz
you need to have the category table in memory (or use a proper enum that is in sync with the values in the db), and set the right categoryid when you do the update / insert command.
if you post the code, we can see if there is any problem there.
CategoryId you want to insert in Product table, should already exist in ProductCategory table.