Django tables connection - django

I have 3 django tables connected like this:
Is there anyway to make a query for table Table that will get id_equip from table equip?
models.py
class Vendor(models.Model):
vendor_name = models.CharField(max_length=50)
def __str__(self):
return self.vendor_name
class Equipment(models.Model):
equipment_name = models.CharField(max_length=50)
id_vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None)
def __str__(self):
return self.equipment_name
class Table(models.Model):
table_name = models.CharField(max_length=100)
id_vend = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None)
id_equip = models.ManyToManyField(Equipment)

This part of the django docs is relevant and helpful, I definitely recommend your review at least that section and ideally the whole page.
Your models are already denormalized as evidenced by Table.id_equip which relates to Equipment so you could do:
table = Table.objects.get(SOME_FILTER)
equipment_ids = list(table.id_equip.all().values_list('id', flat=True))
If you wanted to go through the vendor I'd suggest:
table = Table.objects.get(SOME_FILTER)
equipment_ids = list(Equipment.objects.filter(vendor_set__table_set=table).values_list('id', flat=True))
I would recommend that you don't name your relationship fields with id_. With an ORM, these fields should represent the instances of the Model they are mapping to. For example:
class Table(models.Model):
name = models.CharField(max_length=100)
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None)
equipment = models.ManyToManyField(Equipment)
If you're trying to create the model on top of an existing table, you can make use of the db_column parameter when defining the field.
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, db_column="id_vend")

Related

Django Sum in Annotate

Good afternoon,
I am really struggling with getting a sum using Annotate in DJango.
I am using User object and the following models:
class Depts(models.Model):
dept_name = models.CharField(max_length=55)
dept_description = models.CharField(max_length=255)
isBranch = models.BooleanField(default=False)
def __str__(self):
return "{}".format(self.dept_name)
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile')
title = models.CharField(max_length=75)
dept = models.ForeignKey(Depts, on_delete=models.CASCADE, related_name="dept", null=True)
class ActivityLog(models.Model):
activity_datetime = models.DateTimeField(default=timezone.now)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='activity_user')
activity_category = models.ForeignKey(ActivityCategory, on_delete=models.CASCADE, null=True, related_name='activity_cat')
activity_description = models.CharField(max_length=100, default="Misc Activity")
class ActivityCategory(models.Model):
activity_name = models.CharField(max_length=40)
activity_description = models.CharField(max_length=150)
pts = models.IntegerField()
def __str__(self):
return '%s' % (self.activity_name)
What I need to do is get a group of departments with aggregating the sum of the pts earned by all the users activitylogs.
So a user is part of department, they do activities, each activity is of a type activity_category and has associated points. How can I query using the ORM to get a sum of points for everyone in each department?
Thank you, I cannot seem to wrap my mind around it.
You annotate the departments with the sum:
from django.db.models import Sum
Depts.objects.annotate(
total_pts=Sum('dept__user__activity_user__activity_category__pts')
)
Note: The related_name=… parameter [Django-doc]
is the name of the relation in reverse, so from the Depts model to the UserProfile
model in this case. Therefore it (often) makes not much sense to name it the
same as the forward relation. You thus might want to consider renaming the dept relation to userprofiles.
After setting the related_name='userprofiles', the query is:
from django.db.models import Sum
Depts.objects.annotate(
total_pts=Sum('userprofiles__user__activity_user__activity_category__pts')
)

Django, Sqlalchemy: Cannot drop table ganalytics_article because other objects depend on it

I have this models in my Django ganalytics app:
class Article(models.Model):
id = models.IntegerField(unique=True, primary_key=True)
article_title = models.CharField(max_length=250)
article_url = models.URLField(max_length=250)
article_pub_date = models.DateField()
class Company(models.Model):
company_name = models.CharField(max_length=250)
class Author(models.Model):
author_sf_id = models.CharField(max_length=20, null=True)
author_name = models.CharField(max_length=250)
class AuthorArticleCompany(models.Model):
author = models.ForeignKey(Author,
to_field="id",
on_delete=models.CASCADE,
related_name='authorarticle_author_id')
company = models.ForeignKey(Company,
to_field="id",
on_delete=models.CASCADE,
related_name='authorarticle_company_id')
article = models.ForeignKey(Article,
to_field="id",
on_delete=models.CASCADE,
related_name='authorarticle_article_id')
class Ganalytics(models.Model):
article = models.ForeignKey(Article,
on_delete=models.CASCADE,
related_name='ganalytics_author_id')
totalview = models.IntegerField()
totalinteractions = models.IntegerField()
class Unsubscribers(models.Model):
email = models.EmailField()
reasonwhy = models.CharField(max_length=90)
I am running pandas to_sql to upload the database:
authorarticlecompanydf.to_sql("ganalytics_authorarticlecompany", con=engine, if_exists="append", index=False)
articledf.to_sql("ganalytics_article",con=engine,if_exists="replace",index=False)
company_name.to_sql("ganalytics_company",con=engine,if_exists="replace",index=False)
authordf.to_sql("ganalytics_author", con=engine,if_exists="replace", index=False)
I am getting this error message:
DETAIL: constraint ganalytics_ganalytic_article_id_d37f2464_fk_ganalytic on table ganalytics_ganalytics depends on table ganalytics_article
constraint ganalytics_authorart_article_id_7f4ff374_fk_ganalytic on table ganalytics_authorarticlecompany depends on table ganalytics_article
HINT: Use DROP ... CASCADE to drop the dependent objects too.
[SQL:
DROP TABLE ganalytics_article]
I have tried to change the on_delete field to different values but it wont help.
What am I doing wrong?
What is the command you are running to get the error? The bottom line is Ganalytics depends on Article via the FK between them. By dropping Article first you are breaking that dependency. You either need to DROP Ganalytics first and then Article or follow the hint DROP ... CASCADE. Though be aware that will DROP Ganalytics also.
UPDATE
Another option would be to drop the FK between the two tables. Then you would not have the dependency issue.

Django - query the records in all tables that have the foreign key equal to the selected record in the main table

In Django I want to query the records in all tables that have the foreign key project = ProjectMain's chosen pk. So if I choose a record in ProjectMain and it's pk=2 I also want the records from the other three tables where the foreign key product=2.
Tables Methods, Things, and MoreStuff can have multiple records with project=2.
Here are the tables:
class ProjectMain(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.CharField(max_length=60)
product = models.ForeignKey(ProductType, on_delete=models.CASCADE)
filler = models.CharField(max_length=100)
class Methods(models.Model):
method_name = models.CharField(max_length=10)
method_test = models.CharField(max_length=50, null=False)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)
class Things(models.Model):
thing1 = models.CharField(max_length=10)
thing2 = models.CharField(max_length=50, null=False)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)
class MoreStuff(models.Model):
stuff1 = models.CharField(max_length=10)
stuff2 = models.CharField(max_length=50, null=False)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)
I've been trying Django querysets and am getting nowhere. Please help.
You can access them via the related_name property as defined in ForeignKey.
project_main = ProjectMain.objects.get(id=2)
methods = project_main.methods_set.all() # All the Methods related to the instance
things = project_main.things_set.all() # All the Methods related to the instance
more_stuffs = project_main.morestuff_set.all() # All the Methods related to the instance

How to fetch translation record in django

I am new in django framework.I have 3 tables in mysql database. I want to fetch data from main table with translation table and images table.
My model.py
class Country(models.Model):
#id = models.IntegerField(primary_key=True)
iso_code = models.CharField(max_length=2, unique=True)
slug = models.CharField(max_length=255, unique=True)
is_featured = models.IntegerField(max_length=1)
class Meta:
db_table = 'rh_countries'
class CountryTranslation(models.Model):
country_id = models.ForeignKey(Country, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
locale = models.CharField(max_length=2)
class Meta:
db_table = 'rh_countries_translations'
class CountryImage(models.Model):
country_id = models.ForeignKey(Country, on_delete=models.CASCADE)
image = models.CharField(max_length=255)
is_main = models.IntegerField(max_length=1)
class Meta:
db_table = 'rh_country_images'
Now I want to fetch all country with translation record by locale and associated image.
Please give a solution if anyone know.
You can do this by using a filtering, and annotate:
from django.db.models import F
Country.objects.filter(
countrytranslation__locale=mylocale
).annotate(
name=F('countrytranslation__name')
)
This will result in a QuerySet with all Countrys (that have a Translation for the given mylocale). These Countrys will have an extra attribute .name that is the translated name of the Country.
So given the translations exist, then for mylocale='en', this will result in a QuerySet, with Country(name='Germany', iso_code='de'), and for mylocale='de', it will result in Country(name='Deutschland', iso_code='de') (here this is a bit an ad hoc format, to demonstrate how it works).
Note: ForeignKeys typically do not end with _id. Django will automatically add an _id suffix to the database column. The foreign key itself is on the Python/Django level represented as a lazy loaded attribute.

I am working with Django, During inserting data into database i caught such error

I'm working with django, during inserting data into tables the error is generates as given below...
Error:
int() argument must be a string, a bytes-like object or a number, not 'Tbl_rule_category', How can we solve such error?
view.py
dataToRuleCtgry = Tbl_rule_category(category=category, created_by="XYZ",created_date=datetime.date.today())
dataToRuleCtgry.save()
dataToRule = Tbl_rule(rule_name=rule_name, closure=closure,category_id=Tbl_rule_category.objects.latest('category_id'), created_by="XYZ",created_date=datetime.date.today(), updated_by="XYZ", updated_date=datetime.date.today(), rule_type=rule_type, fk_tbl_rule_tbl_rule_category_id=Tbl_rule_category.objects.latest('category_id'))
dataToRule.save()
models.py
class Tbl_rule_category(models.Model):
category_id = models.AutoField(primary_key=True)
category = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
def __str__(self):
pass # return self.category, self.created_by
class Tbl_rule(models.Model):
rule_id = models.AutoField(primary_key=True)
rule_name = models.CharField(max_length=50)
closure = models.CharField(max_length=50)
category_id = models.IntegerField()
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
updated_by = models.CharField(max_length=50)
updated_date = models.DateField(auto_now=True)
rule_type = models.CharField(max_length=50)
fk_tbl_rule_tbl_rule_category_id = models.ForeignKey(Tbl_rule_category,on_delete=models.CASCADE, related_name='fk_tbl_rule_tbl_rule_category_id_r')
def __str__(self):
return self.rule_name, self.closure, self.created_by, self.updated_by, self.rule_type
The error is occurring because the following is trying to add an object into an integer field: category_id=Tbl_rule_category.objects.latest('category_id')
You could just add: category_id=dataToRuleCtgry.get('category_id') or category_id=dataToRuleCtgry.category_id which will solve the error.
You also don't need to add: created_date=datetime.date.today() because your model defines auto_now=true.
As mentioned you should also amend the def __str__(self): to return a string.
https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.str
Alternatively
You could just add the object link directly to your foreign key for the category model.fk_tbl_rule_tbl_rule_category_id=dataToRuleCtgry. You would no longer need the integer field category_id.
It would be better practice to use the model field name category_id instead of fk_tbl_rule_tbl_rule_category_id. This would mean deleting category_id and then rename fk_tbl_rule_tbl_rule_category_id to category_id.
In Django, the ORM takes care of the basic database details for you; which means in your code you really don't have to worry about individual row ids for maintaining foreign key relationships.
In fact, Django automatically assigns primary keys to all your objects so you should concentrate on fields that are relevant to your application.
You also don't have to worry about naming fields in the database, again Django will take care of that for you - you should create objects that have fields that are meaningful to users (that includes you as a programmer of the system) and not designed for databases.
Each Django model class represents a object in your system. So you should name the classes as you would name the objects. User and not tbl_user. The best practice is to use singular names. Django already knows how to create plural names, so if you create a model class User, django will automatically display Users wherever it makes sense. You can, of course, customize this behavior.
Here is how you should create your models (we will define __str__ later):
class RuleCategory(models.Model):
name = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
class Rule(models.Model):
name = models.CharField(max_length=50)
closure = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
updated_by = models.CharField(max_length=50)
updated_date = models.DateField(auto_now=True)
rule_type = models.CharField(max_length=50)
category = models.ForeignKey(RuleCategory,on_delete=models.CASCADE)
Django will automatically create any primary or foreign key fields, and any intermediary tables required to manage the relationship between the two models.
Now, to add some records:
new_category = RuleCategory(name='My Category', created_by='XYZ')
new_category.save()
# Another way to set values
new_rule = Rule()
new_rule.name = 'Sample Rule'
new_rule.closure = closure
new_rule.created_by = 'XYZ'
new_rule.updated_by = 'XYZ'
new_rule.rule_type = rule_type
new_rule.category = new_category
new_rule.save()
Note this line new_rule.category = new_category - this is how we link two objects. Django knows that the primary key should go in the table and will take care of that automatically.
The final item is customizing the models by creating your own __str__ method - this should return some meaningful string that is meant for humans.
class RuleCategory(models.Model):
name = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
def __str__(self):
return '{}'.format(self.name)
class Rule(models.Model):
name = models.CharField(max_length=50)
closure = models.CharField(max_length=50)
created_by = models.CharField(max_length=50)
created_date = models.DateField(auto_now_add=True)
updated_by = models.CharField(max_length=50)
updated_date = models.DateField(auto_now=True)
rule_type = models.CharField(max_length=50)
category = models.ForeignKey(RuleCategory,on_delete=models.CASCADE)
def __str__(self):
return '{} for category {}'.format(self.name, self.category)
If you notice something, I just put self.category in the __str__ for the Rule model. This is because we have already defined a __str__ for the RuleCategory model, which just returns the category name; so now when we print our Rule we created, we will get Sample Rule for category My Category as a result.