How to get name respect to that id form mysql table? - mysql

In my project i have crud like operation, so when i select department i save id of that item , and bind to table to show that inserted records , so when i bind department i want to bind name of that department not that id . pls help me in this..
Model.py
class Department(models.Model):
ACTIVE = 1
INACTIVE = 2
DELETED = 3
STATUS_CHOICES = (
(ACTIVE, 'active'),
(INACTIVE, 'inactive'),
(DELETED, 'deleted'),
)
department_id = models.AutoField(primary_key=True)
department_name = models.CharField(max_length=30, null=False)
created_on = models.DateTimeField(auto_now_add=True, null=False)
created_by = models.CharField(max_length=100, null=False)
modified_on = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=100)
status = models.CharField(max_length=10, null=False, choices=STATUS_CHOICES)
objects = UserManager()
class Meta:
managed = True
db_table = "ht_department"
def __str__(self):
return self.department_id
forms.py
class EmpForm(ModelForm):
class Meta:
model = Employee
fields = ["employee_id", "Name", "designation", "department_id", "manager_id",
"date_of_joining","date_of_birth", "location_id", "email", "contact_number",
"password", "created_by", "modified_by", "status", "user_type"]
class dept(ModelForm):
class Meta:
model = Department
fields = ["department_id", "department_name", "created_by", "modified_by", "status"]
class EmpLoc(ModelForm):
class Meta:
model = Location
fields = ["location_id", "location_name", "created_by", "modified_by", "status"]
html
<tbody id="myTable">
{% for employee in employees %}
<tr>
<td>{{ employee.employee_id}}</td>
<td>{{ employee.Name}}</td>
<td>{{ employee.designation}}</td>
<td>{{ employee.department_id}}</td>
<td>{{ employee.manager_id}}</td>
<td>{{ employee.location_id}}</td>
<td>
<i class="material-icons" data-toggle="tooltip" title="Edit"></i>
<i class="material-icons" data-toggle="tooltip" title="Delete"></i>
</td>
</tr>
{% endfor %}
</tbody>
Here is my updated code for EmployeeModel:
Employee Model (Updated)
class Employee(models.Model):
ACTIVE = 1
INACTIVE = 2
DELETED = 3
STATUS_CHOICES = (
(ACTIVE, 'active'),
(INACTIVE, 'inactive'),
(DELETED, 'deleted'),
)
USER_TYPE = (
(1, 'user'),
(2, 'hr'),
)
employee_id = models.CharField(max_length=15, primary_key=True)
Name = models.CharField(max_length=100, null=False)
designation = models.CharField(max_length=30, null=False)
department_id = models.IntegerField(null=False)
manager_id = models.CharField(max_length=15, null=False)
date_of_joining = models.DateField(null=False)
date_of_birth = models.DateField(null=False)
location_id = models.IntegerField(null=False)
email = models.EmailField(max_length=100, unique=True,
null=False)
contact_number = models.CharField(max_length=10 , unique=True,
null=False)
password = models.CharField(max_length=100, null=False)
created_on = models.DateTimeField(auto_now_add=True)
created_by = models.CharField(max_length=100, null=False)
modified_on = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=100, null=True)
status = models.CharField(max_length=10, null=False,
choices=STATUS_CHOICES)
user_type = models.CharField(max_length=10, choices=USER_TYPE)
objects = UserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["Name"]
is_anonymous = "FALSE"
is_authenticated = "TRUE"
class Meta:
managed = True
db_table = "ht_employee"

You should update the department_id field in the employee as a foreign key in order to get the name of the department so it will be as:
class Employee(models.Model):
department = models.ForeignKey(Department)
and then to get the department name in template
{{employee.department.department_name}}

Related

Django multiple table query - convert MySQL to Django (Python) query

I need to figure out how to translate MySQL query into Django (Python) language. Any help? Basically I need to get the total from each table plus the remain total after spend.
class Trip(models.Model):
name = models.CharField('Name', max_length=254)
class Account(models.Model):
name = models.CharField('Name', max_length=254)
class Wallet(models.Model):
trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT)
incoming_date = models.DateField(verbose_name='Incoming Date')
total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True)
account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT)
class Expense(models.Model):
trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT)
outcome_date = models.DateField(verbose_name='Outcome Date')
total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True)
account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT)
SELECT *, (wallet_total - expense_total) AS remain_total
FROM (
SELECT account.name, SUM(wallet.total) AS wallet_total
FROM account
INNER JOIN wallet
ON wallet.account_id = account.id
WHERE wallet.trip_id=4
GROUP BY account.name
) AS wallet,
(
SELECT account.name, SUM(expense.total) AS expense_total
FROM account
INNER JOIN expense
ON expense.account_id = account.id
WHERE expense.trip_id=4
GROUP BY account.name
) AS expense;
If you want an explanation, comment below ^_^
from django.db.models import Sum
class Trip(models.Model):
name = models.CharField('Name', max_length=254)
class Account(models.Model):
name = models.CharField('Name', max_length=254)
class Wallet(models.Model):
trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT)
incoming_date = models.DateField(verbose_name='Incoming Date')
total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True)
account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT)
class Expense(models.Model):
trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT)
outcome_date = models.DateField(verbose_name='Outcome Date')
total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True)
account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT)
trip_id = 4
wallet_total = Wallet.objects.filter(trip_id=trip_id).values('account__name').annotate(wallet_total=Sum('total'))
expense_total = Expense.objects.filter(trip_id=trip_id).values('account__name').annotate(expense_total=Sum('total'))
results = []
for w in wallet_total:
for e in expense_total:
if w['account__name'] == e['account__name']:
results.append({
'account__name': w['account__name'],
'wallet_total': w['wallet_total'],
'expense_total': e['expense_total'],
'remain_total': w['wallet_total'] - e['expense_total']
})
class ReportAccount(LoginRequiredMixin, GroupRequiredMixin, AccessMixin, ListView):
paginate_by = 12
template_name = 'report_account.html'
context_object_name = 'queryset'
login_url = '/login/'
redirect_field_name = 'redirect_to'
group_required = u'users'
raise_exception = True
def get_queryset(self):
user = get_current_user()
userselectedtrip = SelectedTrip.objects.filter(created_by=user)
if userselectedtrip.exists():
trip_id = SelectedTrip.objects.get(created_by=user).trip.id
else:
trip_id = 1
wallet_total = Wallet.objects.filter(trip_id=trip_id).values('account__name').annotate(wallet_total=Sum('total'))
expense_total = Expense.objects.filter(trip_id=trip_id).values('account__name').annotate(expense_total=Sum('total'))
qs = []
for w in wallet_total:
for e in expense_total:
if w['account__name'] == e['account__name']:
qs.append({
'account__name': w['account__name'],
'wallet_total': w['wallet_total'],
'expense_total': e['expense_total'],
'remain_total': w['wallet_total'] - e['expense_total']
})
# break
return qs
Template
<tbody>
{% for report in queryset %}
<tr style="background-color:#ffffff";>
<td>{{ report.account__name }}</td>
<td>{{ report.wallet_total |default_if_none:0 }}</td>
<td>{{ report.expense_total |default_if_none:0 }}</td>
<td>{{ report.remain_total |default_if_none:0 }}</td>
</tr>
{% endfor %}
</tbody>

qlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Users.rater

i am trying to create function in FLASK and html page to allow users to rate each other - one user can give rating to enother user, but i am getting this error: sqlalchemy.exc.AmbiguousForeignKeysError. Does anyone know, how to solve it please?
class Users(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(20), nullable=False, unique=True)
name = db.Column(db.String(200), nullable = False)
email = db.Column(db.String(120), nullable = False, unique = True)
date_added = db.Column(db.DateTime, default = datetime.utcnow)
password_hash = db.Column(db.String(128))
posts = db.relationship('Posts', backref='poster')
place = db.Column(db.String(128))
rater = db.relationship('Ratings', backref='rater')
rated = db.relationship('Ratings', backref='rated')
class Ratings(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200))
from_user = db.Column(db.Integer, db.ForeignKey('users.id'))
to_user = db.Column(db.Integer, db.ForeignKey('users.id'))
#app.route('/user/<int:id>/add-rating/', methods=['GET', 'POST'])
def rating(id):
form = RatingForm()
to_user = Users.query.get_or_404(id)
if form.validate_on_submit():
from_user = current_user.id
content = form.content.data
rating = Ratings(from_user=from_user, to_user=to_user, content=content)
db.session.add(rating)
db.session.commit()
flash(' posted')
return render_template('add_rating.html', form=form, to_user=to_user)

How to Get Unique Record for each category in django

I have a table called product_type & Product.
class Product_type(models.Model):
product_type_id = models.AutoField(primary_key=True)
product_type_name = models.CharField(max_length=255, null = False, unique=True)
product_type_title = models.CharField(max_length=255, null = True)
product_type_description = models.TextField(null = False)
product_type_slug = models.SlugField(unique=True, blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product_name = models.CharField(max_length=255, null = False, unique=True)
product_slug = models.SlugField(unique=True, blank=True, null=True)
product_title = models.CharField(max_length=255, null = True)
product_info = models.TextField(null = False)
product_description = models.CharField(max_length = 255)
product_price = models.CharField(max_length = 255)
brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True)
product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
product_status = models.CharField(max_length = 100, default = "publish")
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
class Brand(models.Model):
brand_id = models.AutoField(primary_key=True)
brand_name = models.CharField(max_length=255, null = False, unique=True)
brand_slug = models.SlugField(unique=True, blank=True, null=True)
brand_title = models.CharField(max_length = 255)
brand_logo = models.ImageField(upload_to = 'brand/logo/%Y/%m/')
brand_logo_alt_text = models.CharField(max_length=255, null = False)
brand_info = models.TextField(null = False)
brand_description = models.CharField(max_length = 255)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
country = models.ForeignKey(Country, default = '1', on_delete=models.SET_DEFAULT, null=True)
brand_status = models.CharField(max_length = 100, default = "publish")
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
in product table I've linked brand table as brand and product_type table as product_type, so suppose I've multiple records for each brand in product table. So I only want 1 record for each brand which has a lowest product_price and that record must match with product_type.
for example:
I want only those product which contains product_type = 'accounting'.
so here is a demo data:
product(model data)
product_id:1,product_name:abc, product_type: accounting, brand:aaa, price:$100
product_id:2,product_name:xyz, product_type: accounting, brand:aaa, price:$50
product_id:3,product_name:bdf, product_type: accounting, brand:bbb, price:$150
product_id:4,product_name:ghf, product_type: other, brand:ccc, price:$150
so my query result will be product_id 2,3 because 1,2 have same brand but 2 has the lowest price & 2,3 both have product_type = accounting.
I tried too much but nothing works.
I want your help!
First, use models.DecimalField for product prices. Do not use models.CharField for numbers. Change the product_price field to product_price = models.DecimalField(max_digits=6, decimal_places=2) (Stores $0 to $9999.99).
Then, you can try the following:
from django.db.models import F, Min
Product.objects.filter(
product_type=my_product_type
).annotate(
min_brand_price=Min('brand__product_type__product_price')
).filter(
product_price=F('min_brand_price')
)
Other related questions on StackOverflow:
How to get only latest record on filter of foreign key django
Django model get unique foreign key rows based on other column max value

How to connect all related DB with FK in Django?

I got problem in making Queries. In the shell I all the time faced 'user' has no split error. and want to know how to make query about those models.
select i.id, i.name, i.email, i.memo, g.id, g.name, i.birthday, i.regdt, n.number, t.name, t.id
from webcontact_info as i
inner join webcontact_number as n on i.id = n.info_id
inner join webcontact_group as g on i.group_id = g.id
inner join webcontact_type as t on n.type_id = t.id;
this query in mysql. how can i change into query for Django?
please help me about this.
those are models.py
class Group(models.Model):
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Type(models.Model) :
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Info(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(null=True, blank=True, unique=True)
memo = models.CharField(max_length=200, null=True)
birthday = models.CharField(max_length=12,null=True, blank=True)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
class Number(models.Model):
number = models.CharField(max_length=11)
info = models.ForeignKey(Info, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
type = models.ForeignKey(Type, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
You can just use your related object with your object. But maybe you're looking for select_related.
It will return selecting additional related-object data - It will boost query performance bit much.
infos = Info.objects.select_related('user', 'group', 'user__number').
Check more detail in django docs

Is it possible re-write `raw-sql` to `django-orm`?

I need to re-write raw-sql to django-orm. But unfortunately I can't do it. Does someone has ideas ?:
HttcOrder.objects.raw('''SELECT httc_order.id, httc_order.price, httc_order.quantity,
SUM(markedskraft_trade.qty) as positions_quantity
FROM httc_order left outer join markedskraft_trade on httc_order.id = markedskraft_trade.httc_order_id
WHERE httc_order.order_status in ('new', 'pending', 'confirmed')
and httc_order.mk_contract_id = %s
group by httc_order.id
having positions_quantity is NULL or quantity - positions_quantity > 0
order by httc_order.price desc''', [contract.id])
Example of models:
httc:
class Order(models.Model):
quantity = models.IntegerField(verbose_name=_('Qty'))
order_status = models.CharField(max_length=10, choices=ORDER_STATUSES, default=NEW)
price = models.IntegerField(verbose_name=_('Prc'))
mk_contract = models.ForeignKey(
Contract, related_name='httc_orders', verbose_name=_('Markedskraft contract')
)
....
markedskraft:
class Trade(models.Model):
order_id = models.IntegerField(blank=True, null=True, db_index=True)
httc_order_id = models.ForeignKey(HttcOrder, blank=True, null=True, db_index=True)
qty = models.IntegerField()
.......