how to update data into table in sql database using django - sql

I have learned about the database concepts in django tutorial book. I have some doubts about to fetch data from the table in sql database server. In django book they explained something like this to filter data as like as below
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
Here Entry is the class name which is defined in models.py file like below
models.py
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()
def __str__(self): # __unicode__ on Python 2
return self.headline
In the above method there is nothing mention about the table to modified. Then which table it is going to be modified in the below query.
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
If i asked anything wrong please forgive me. Can anyone clear my doubts.

From the docs on table names:
To save you time, Django automatically derives the name of the database table from the name of your model class and the app that contains it. A model’s database table name is constructed by joining the model’s “app label” – the name you used in manage.py startapp – to the model’s class name, with an underscore between them.
For example, if you have an app bookstore (as created by manage.py startapp bookstore), a model defined as class Book will have a database table named bookstore_book.
To override the database table name, use the db_table parameter in class Meta.
You don't need to know the table name, if you use the API like you have listed:
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
Django will know what table to update, because of the model you have referenced.

The name of table is determined by model parameter "table_name". If you don't specified it, django automatically derives the name of the database table from the name of your model class and the app that contains it: https://docs.djangoproject.com/en/dev/ref/models/options/#db-table
If your question is about performing SQL queries in django, this will be helpful: https://docs.djangoproject.com/en/dev/topics/db/sql/

Related

Odoo 15 Find tax_ids Inside the account.move.line (Invoice) Model

Good day, hope everything's well.
I'm trying to find the value of tax_ids (Many2many field) inside the account.move.line model but i can't seems to find anything. I already access the psql of the database but i cant find tax_ids too.
I accessed that account.move.line model with ORM like this :
def _post(self, soft=True):
for move in self:
....
account_move_line = self.env['account.move.line'].search([('id', '=', int(move.id))])
print(account_move_line.tax_ids) #this find nothing
could someone please elaborate how is it possible to access id of the tax that applied to, in this case, an invoice line record?
Edit : Sometimes this ORM fetching the ID and sometimes it doesn't. But most likely it's not fetching.
I'm trying to find the value of tax_ids (Many2many field) inside the
account.move.line model but i can't seems to find anything. I already
access the psql of the database but i cant find tax_ids too.
tax_ids in account.move.line model is a Many2Many field, which is stored separately as another table in the database. This kind of relation field mostly be named something like this (main_table)_(related_table)_rel (ignore the parentheses). For example, this particular case's table is account_move_line_account_tax_rel since its main table is account_move_line and the related table for that specific field is account_tax. Inside the relation table, you will almost always find 2 fields mapping both ids together. For this case, it is going to be account_move_line_id and account_tax_id.
I accessed that account.move.line model with ORM like this :
def _post(self, soft=True):
for move in self:
....
account_move_line = self.env['account.move.line'].search([('id', '=', int(move.id))])
print(account_move_line.tax_ids) #this find nothing could someone please elaborate how is it possible to access id of the tax
that applied to, in this case, an invoice line record?
Edit : Sometimes this ORM fetching the ID and sometimes it doesn't.
But most likely it's not fetching.
Accessing a field via ORM always works as you intended if it is implemented correctly. In your code, you are searching account_move_line by id but you are trying to search it with move.id, which I assume it is account_move since you got the data sometimes. If you can access the lines that you want correctly, you will see that account_move_line.tax_ids will always give you the correct tax_ids. From what your code looks, I think you are trying to search the lines by its account_move. Therefore, your domain should be [('move_id', '=', int(move.id))] instead.

Django Admin: Intersection (Natural Inner Join) between Two Models

I'm a Django beginner. I have two models that I would like to display as one table in the Django admin interface. Below are the simplified versions of the models:
class Final_Application_Personal_Detail(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=20)
id_no = models.CharField(max_length=14)
class Final_Application_Beneficiary_Detail(models.Model):
user = models.ForeignKey(User)
beneficiary_name = models.CharField(max_length=20)
beneficiary_id_no = models.CharField(max_length=14)
I suppose because these two models conceptually form part of one form (a Final_Application form), I could have maybe used Django's formwizard - however, because in reality both personal details and beneficiary details are quite a lot to fill in, I thought I'd want to give the user a chance to fill them in separately (in django formwizard, as far as I know, if the user doesn't fill out all the data at once, then all previous data is also lost because the form can't be saved with unvalidated fields).
I want to join the two models in Django admin so that the administrative user can see all a user's information (personal details and beneficiary's details) on one page. So, I'd like to do an inner join on the above-mentioned tables on the field 'user'. The SQL would look like this:
SELECT *
FROM Final_Application_Personal_Detail
JOIN Final_Application_Beneficiary_Detail
ON Final_Application_Personal_Detail.user = Final_Application_Beneficiary_Detail.user
With regards to Django's ORM, I've looked into the keyword argument related_to in order to join the tables. I don't think that will work, however...it seems as if 'select_related' is just another way to stipulate a foreign key. I now want to use raw SQL in order to join the tables. I've tried using the cursor function to implement raw SQL, but I don't quite know how to implement it so that the output shows in Django's admin interface. Also, I'm a little bit afraid of using raw SQL, because as far as I understand, raw SQL can introduce security risks (I've read that Django's ORM prevents SQL injections).
Thank you for your help.
You can't do this with django admin. However, you can use inlines to edit both models in the User admin.
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
class Final_Application_Personal_DetailInline(admin.StackedInline):
model = Final_Final_Applicationl_Detail
class Final_Application_Beneficiary_DetailInline(admin.StackedInline):
model = Final_Final_Application_Beneficiary_Detail
admin.site.unregister(User)
#admin.register(User)
class CustomUserAdmin(UserAdmin):
inlines = [
Final_Application_Personal_DetailInline,
Final_Application_Beneficiary_DetailInline,
]

How to create a database table based off a list

I am using Flask/Django to create my database model so I understand Python code but SQL is fine as well.
I was wondering how I can create a database filled with options from a list in that database and I was hoping someone could point me in the right direction or give me an example.
This is going to be a REST API and I want the data to be returned in JSON as well as use curl to test it.
E.g. What I want the tables to look like
Food:
Apples
Oranges
Pears
Sugar
Recipe:
Description: Baked Pears (can be changed by user)
Needs: Pears, Sugar
(User can only choose from the Food list)
User sends request to the API to create a new recipe. It calls the list of food options and the Javascript client lists those options to choose from. Then the user posts his recipe to the database. I am lost how to have the database relate the Food items to the created Recipes.
Sounds like you would need to use Django's many to many relationship. In your example, the Recipe would contain a many to many relationship to the Food.
from django.db import models
class Food(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Recipe(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
ingredients = models.ManyToManyField(Food)
def __str__(self):
return self.title
Django 1.7 Docs: many_to_many

Django 1.6 and Tastypie, joining tables

Basically I want to join a bunch of tables together and display it, My tables are sort of as follows:
class A(models.Model):
name = models.CharField(max_length=60)
class B(models.Model):
a = models.ForeignField(A)
class C(models.Model):
a = models.ForeignField(A)
class D(models.Model):
a = models.ForeignField(A)
This is the basic structure of my system, I want to join all the tables with the foreign field to the table A.
I want to also be able to display in xml using Tastypie, aka ?format=xml, I have been able to display one table on its own but it seems like it is impossible to do the type of join I want even though it would be a very simple SQL query.
I have found an answer to this problem elsewhere: http://djangoandlove.blogspot.com/2012/11/tastypie-following-reverse-relationship.html

Django queries: how to annotate with a filtered count?

Suppose I have a Book model with a language field and a foreign key to a Publisher model.
Currently I use a Count annotation in a custom Publisher manager to allow me to add to the admin a sortable column with the number of books by each publisher. (see How to add a sortable count column to the Django admin of a model with a many-to-one relation? )
My problem now is that I need to have a different column count for the books published in each language.
Is there any way to make the annotation subject to a filter of the related model?
You can use the double underscore __ for this purpose. Something like this (snippet taken from question linked to by OP):
class PublisherManager(models.Manager):
def get_query_set(self):
return super(PublisherManager,self).get_query_set().annotate(lang_count=Count('book__language'))