Django Model, Referenced via Text Fields (without the fields ending in '_id') - python

I am inheriting a poorly designed DB as I port code from PHP to Django/Python. Redesign the database is a constraint on this project, and as such is off the table completely. I have two tables that are referenced via a text field
class MemberCompany(models.Model):
id = models.IntegerField(primary_key=True)
company_name = models.TextField(blank=True)
ticker = models.CharField(max_length=45L, blank=True, unique=True)
primary_address = models.TextField(blank=True)
industry_classification = models.TextField(blank=True)
website = models.TextField(blank=True)
industry_id = models.IntegerField(null=True, blank=True)
business_description = models.TextField(blank=True)
dodilio_class = models.TextField(blank=True)
category_id = models.IntegerField(null=True, blank=True)
parent_industry_id = models.IntegerField(null=True, blank=True)
phone = models.CharField(max_length=20L, blank=True)
country_listing = models.CharField(max_length=255L, blank=True)
exchange = models.CharField(max_length=45L, blank=True)
class Meta:
db_table = 'member_companies'
class TeaserTickers(models.Model):
id = models.IntegerField(primary_key=True)
teaser = models.ForeignKey(Idea, related_name='tickers')
######################################################v
# This works to return the ticker text
#ticker = models.CharField(max_length=135L, blank=True)
######################################################v
# This returns: "Unknown column 'teaser_tickers.ticker_id' in 'field list'"
#ticker = models.ForeignKey(MemberCompany, to_field='ticker')
######################################################v
# This returns: "Unknown column 'teaser_tickers.ticker_id' in 'field list'"
ticker = models.ForeignKey(MemberCompany, to_field='ticker')
date_added = models.CharField(max_length=135L, blank=True)
class Meta:
db_table = 'teaser_tickers'
How do I form a foreign key relationship between the two tables / model classes if the database doesn't follow the django naming convention.
I tried defining my own relationship, but that had issues too (for some reason it wasn't querying MemberCompany and instead was attempting to push the ticker value (e.g. 'AAPL') onto a stack of MemberCompany. But here is the code for that:
class ImproperlyNamedForeignKey(djangoRelated.ForeignKey):
def get_attname(self):
return self.name

May be this would help:
ticker_id = models.CharField(
max_length=255,
blank=True,
db_index=True,
db_column='ticker'
)
ticker = models.ForeignKey(MemberCompany, to_field='ticker')
If this doesn't help, please consider these useful links:
https://docs.djangoproject.com/en/dev/howto/legacy-databases/
http://www.djangobook.com/en/2.0/chapter18.html

Related

How to access model from Foreign Key, Django?

I have 2 models in my project. What I want to do is access CustomUser model field "user_coins". But the problem is that I need to get it with only having offer_id from the TradeOffer model. So essentially what I would like to happen is to find the TradeOffer field with offer_id and through ForeignKey get the CustomUser field user_coins that the offer_id belongs to. I can't seem to figure out how to do that.
class CustomUser(AbstractUser):
username = models.CharField(max_length=32, blank=True, null=True)
name = models.CharField(max_length=200, unique=True)
user_coins = models.FloatField(default=0.00)
class TradeOffers(models.Model):
name = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
offer_id = models.CharField(max_length=150, unique=True)
offer_state = models.IntegerField()
offer_message = models.TextField(null=True)
trade_id = models.CharField(max_length=150, unique=True, null=True)
date_added = models.DateTimeField(auto_now_add=True)
Simple. To get the "user_coins" through "TradeOffers" objects you have to do this:
tradeoffer = TradeOffers.objects.get(offer_id = <whatever>) #Get the object.
user_coins = tradeoffer.name.user_coins #Get the user_coins field.
Or directly:
user_coins = TradeOffers.objects.get(offer_id = <whatever>).name.user_coins

What is the best way to handle different but similar models hierarchy in Django?

What is the deal: I'm crating a site where different types of objects will be evaluated, like restaurants, beautysalons, car services (and much more).
At the beginning I start with one app with with Polymorfic Model:
models.py:
from django.db import models
from users.models import ProfileUser
from django.utils import timezone
from polymorphic.models import PolymorphicModel
class Object(PolymorphicModel):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2)
created_date = models.DateTimeField(default=timezone.now)
approved_object = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
def __str__(self):
return f"{self.title}"
class Restaurant(Object):
seats = models.IntegerField()
bulgarian_kitchen = models.BooleanField(default=False)
italian_kitchen = models.BooleanField(default=False)
french_kitchen = models.BooleanField(default=False)
sea_food = models.BooleanField(default=False)
is_cash = models.BooleanField(default=False)
is_bank_card = models.BooleanField(default=False)
is_wi_fi = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='restaurants')
category_bg_name = models.CharField(max_length=100, default='Ресторанти')
bg_name = models.CharField(max_length=100, default='Ресторант')
is_garden = models.BooleanField(default=False)
is_playground = models.BooleanField(default=False)
class SportFitness(Object):
is_fitness_trainer = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='sportfitness')
category_bg_name = models.CharField(max_length=100, default='Спорт и фитнес')
bg_name = models.CharField(max_length=100, default='Спорт и фитнес')
class CarService(Object):
is_parts_clients = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='carservice')
category_bg_name = models.CharField(max_length=100, default='Автосервизи')
bg_name = models.CharField(max_length=100, default='Автосервиз')
class Comment(models.Model):
object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
content = models.TextField()
rating = models.TextField()
approved_object = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.content}"
class Images(models.Model):
object = models.ForeignKey(Object, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='attachments',
verbose_name='Image')
class ObjectCoordinates(models.Model):
object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='coordinates')
latitude = models.CharField(max_length=60)
longitude = models.CharField(max_length=60)
Don't mention that name Object is wrong, I already know that :)
So all logic about different objects was in one App and this start to cause some problems, like:
views.py:
def show_object(request, category, pk, page_num):
categories = {'restaurants' : 'Restaurant', 'sportfitness' : 'SportFitness', 'carservice' : 'CarService'} # probably this is not good way to do it
obj = apps.get_model('objects', categories[category]).objects.get(id=pk)
def show_all_objects(request, category, page_num, city=None):
params_map = {
'restaurants': Restaurant,
'sportfitness': SportFitness,
'carservice': CarService,
}
objects = Object.objects.instance_of(params_map.get(category))
and other problems in templates (a lot of if-else blocks) etc.
So I decide to change whole structure and put every model in different app, so now I have app:restaurants, app:sportfitness, app:carservices, etc. But it begin to cause some problems, again, like this model:
class ObjectCoordinates(models.Model):
object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='coordinates')
latitude = models.CharField(max_length=60)
longitude = models.CharField(max_length=60)
All of objects (restaurants, car services) has coordinates of map, so I'm not sure how to handle it, with Model ObjectCoordinates . If I create ObjectCoordinates for each of them, respectively a table in BD (then I will have some tables with different names but same structure, which is not very good, because except ObjectCoordinates, models share and other common models like Images and others, so at the end I will have a lot of tables with different names and same structure). Probably I should add one more column for object category, if I got two rows with same id of objects?
Probably change ObjectCoordinates and other common models to ManyToMany relation will prevent identical tables, but I'm not quite sure about that. Other problem is that there is a lot of repeated code (in views, templates). Also, now, I don't know how to get all objects (restaurants, car services) when they do not have common point, like Object model in first scenario with Polymorphic Model. Or I should keep different apps but to create common Model for all objects, and all of them to to inherit it.
Questions:
What structure is better, first one or second one?
What is the best wayt to implement such site (model structure)?
Should I create common point (model) for all models who they will inherit?
Here is my third attempt (notice that Object is renamed to Venue):
from django.db import models
from users.models import ProfileUser
from django.utils import timezone
from polymorphic.models import PolymorphicModel
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return f"{self.name}"
class Category(models.Model):
name = models.CharField(max_length=20)
bg_name = models.CharField(max_length=20, default=None)
category_bg_name = models.CharField(max_length=100, default=None)
def __str__(self):
return f"{self.name}"
class Venue(models.Model):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2)
created_date = models.DateTimeField(default=timezone.now)
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
venue_category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category')
def __str__(self):
return f"{self.title}"
class VenueFeatures:
seats = models.IntegerField()
bulgarian_kitchen = models.BooleanField(default=False)
italian_kitchen = models.BooleanField(default=False)
french_kitchen = models.BooleanField(default=False)
sea_food = models.BooleanField(default=False)
is_cash = models.BooleanField(default=False)
is_bank_card = models.BooleanField(default=False)
is_wi_fi = models.BooleanField(default=False)
is_garden = models.BooleanField(default=False)
is_playground = models.BooleanField(default=False)
is_fitness_trainer = models.BooleanField(default=False)
is_parts_clients = models.BooleanField(default=False)
is_hair_salon = models.BooleanField(default=False)
is_laser_epilation = models.BooleanField(default=False)
is_pizza = models.BooleanField(default=False)
is_duner = models.BooleanField(default=False)
is_seats = models.BooleanField(default=False)
is_external_cleaning = models.BooleanField(default=False)
is_internal_cleaning = models.BooleanField(default=False)
is_engine_cleaning = models.BooleanField(default=False)
is_working_weekend = models.BooleanField(default=False)
is_kids_suitable = models.BooleanField(default=False)
is_working_weekend = models.BooleanField(default=False)
venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='venue')
class Comment(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
content = models.TextField()
rating = models.TextField()
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.content}"
class Images(models.Model):
venue = models.ForeignKey(Venue, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='attachments',
verbose_name='Image')
class VenueCoordinates(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='coordinates')
latitude = models.CharField(max_length=60)
longitude = models.CharField(max_length=60)
Now I do not now how to use Venue with VenueFeatures
Notice that features are just true/false values (checkboxes in form).
Okay, this is probably the best way to abstract anything as much as I can:
from django.db import models
from users.models import ProfileUser
from django.utils import timezone
from polymorphic.models import PolymorphicModel
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return f"{self.name}"
class Category(models.Model):
name = models.CharField(max_length=20)
bg_name = models.CharField(max_length=20, default=None)
category_bg_name = models.CharField(max_length=100, default=None)
icon = models.CharField(max_length=40, default=None)
def __str__(self):
return f"{self.name}"
class Venue(models.Model):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2)
created_date = models.DateTimeField(default=timezone.now)
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return f"{self.title}"
class Feature(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=100 )
category = models.ForeignKey(Category, on_delete=models.CASCADE)
type = models.CharField(max_length=100)
def __str__(self):
return f"{self.name}"
class VenueFeatures(models.Model): # ManyToMany Venues <-> Features
venue = models.ForeignKey(Venue, on_delete=models.CASCADE)
feature = models.ForeignKey(Feature, on_delete=models.CASCADE)
value = models.CharField(max_length=255)
class Comment(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
content = models.TextField()
rating = models.TextField()
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.content}"
class Images(models.Model):
venue = models.ForeignKey(Venue, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='attachments',
verbose_name='Image')
class VenueCoordinates(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='coordinates')
latitude = models.CharField(max_length=60)
longitude = models.CharField(max_length=60)
Now Features are bound with Categories
Also Venues are ManyToMany with Features
I have already linked it to business logic and it works fine.
TL;DR Use a JSONField (JSONB automatically I think) in PostgreSQL WITHOUT a GIN index for your VenueFeatures instead of creating an entirely new model. Postgres has come a long way towards NoSQL/unstructured DB and it's really good. Using a JSONField in your Venue model would work really well. At the very bottom, I talk about how I would design your site's db.
Although I hate saying this, but this could be the job of a NoSQL database. Usually every application uses RDBM which is structured, but you are using unstructured attributes. You could try using PostgreSQL's JSONB field but... stuffing everything into one field would be tiresome for the GIN index + caching.
For now, I'll ignore a lot of weird practices such as needing to partition a couple of attributes, max_length for char field is typically 255 length for all databases, making sure the most accessed tables don't have too many attributes so that caching is better (i.e. you don't have to invalidate your cache every time a user updates your table), GeoDjango for your coordinate system with the standard Mercator projection system on Postgres Geography mode, and you could use sets instead of dicts (sets are iterables and use {} but nothing is repeated)...
Stay away from this option: For one, I NEVER recommend MongoDB, but it could be useful for you... so long as your application doesn't grow too large as in a couple million records could break your system.
The other RECOMMENDED option is PostgreSQL's JSONB or Django's JSONField withOUT a GIN index (I strongly recommend you don't index this field since venues could change them sooo often to the point that REINDEXING and caching would burn your server and slow your app). It can be useful to store a venue's "Features" inside of this JSONB field since everything is super unstructured.
Lowering the number of attributes is better. You've got A LOT of them too which could slow down querying. I recommend you use Django-cachalot for caching since they support JSONField which can avoid your issue of having a LOT of attributes.
Other recommendations in general
Instead of using default='', just do blank=True, null=True since you're basically saying the user doesn't have to fill out the email field.
Kind of like how you would have a user profile instead of stuffing ALL of your attributes inside of the main User model, you want to partition your Venue data into different models.
The way I would've designed this:
Since you originally had these three venues, just make the "Categories" table into choices.
from django.contrib.gis.db import models # This also imports standard models
from django.contrib.postgres.fields import JSONField # Remember to turn on GeoDjango with PostgreSQL's PostGIS extension
from django.contrib.postgres.indexes import BrinIndex
class Venue(models.Model):
id = models.BigAutoField(primary_key=True)
title = models.CharField(max_length=255)
rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2)
created_date = models.DateTimeField(default=timezone.now)
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
VENUE_TYPES = [
(1, "restaurant"),
(2, "concert"),
(3, "art night")
]
category = SmallPositiveIntegerField(choices=VENUE_TYPES)
location = models.PointField(srid=4326) # mercator projection from GeoDjango. You don't have to use this; you can stick to your old city and address thing
class Meta:
indexes = (
BrinIndex(fields=['category']), # this is in case you have a LOT of categories later on.
)
class VenueProfile(models.Model):
venue = models.OneToOneField(Venue, on_delete=models.CASCADE, primary_key=True)
misc_features = JSONField() # This field is for stuff like your restaurant features OR your concert features. You can put whatever you want in there. Just make sure you have a list of features that people have when trying to access the JSON so you don't run into exceptions.
created_date = models.DateTimeField(auto_now_add=True)
facebook = models.CharField(max_length=100, blank=True, null=True)
instagram = models.CharField(max_length=100, blank=True, null=True)
city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) # SET_NULL in case you accidentally delete a city. You don't want to also delete the venue.
image = models.ImageField(upload_to='attachments',
verbose_name='Image')
# These attributes are universal for ANY venue so that's why they don't need to be in the JSONField
"""
For the rest of the features, I have no concern EXCEPT for city. Because you're using GeoDjango, you should also use MaxMind's free city database to determine location based on coordinates. That way, you've essentially scraped the need to store the user and such. You could probably save the address field since it could make things easier that a simple coordinate. It's really up to you. You could also use both!
"""
The attributes I've added to the Venue model are THE MOST important things in my opinion that a user would immediately want to know about.
The VenueFeature model is something that isn't updated that much. It's PRIME for using Django-cachalot to take over since it's not modified that often. (50 modifications per second makes invalidation of caches per modification a big hassle).
Comments model is fine.

Query using Joins in Django

class Students(models.Model):
id = models.BigAutoField(primary_key=True)
admission_no = models.CharField(max_length=255)
roll_no = models.CharField(unique=True, max_length=50, blank=True, null=True)
academic_id = models.BigIntegerField()
course_parent_id = models.BigIntegerField()
course_id = models.BigIntegerField()
first_name = models.CharField(max_length=20)
middle_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
user_id = models.BigIntegerField()
date_of_birth = models.DateField(blank=True, null=True)
date_of_join = models.DateField(blank=True, null=True)
class Courses(models.Model):
id = models.BigAutoField(primary_key=True)
parent_id = models.IntegerField()
course_title = models.CharField(max_length=50)
slug = models.CharField(unique=True, max_length=50)
tenant_user = models.ForeignKey('Users', models.DO_NOTHING, default='')
course_code = models.CharField(max_length=20)
course_dueration = models.IntegerField()
grade_system = models.CharField(max_length=10)
is_having_semister = models.IntegerField()
is_having_elective_subjects = models.IntegerField()
description = models.TextField()
status = models.CharField(max_length=8)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = True
db_table = 'courses'
def __unicode__(self):
return self.course_title
class StudentProfileSerializer(ModelSerializer):
class Meta:
model = Students
depth = 0
fields = '__all__'
The first two tables/class contains the course and student table and the third contains the serializer. Can anyone please help how to query using the joins in django. I need to fetch the course_title from Courses table and first_name from Students table.
IMHO, you should review your models; course_id in Students should be a course=models.ForeignKey('Courses', ...); this way you can refer to the course title using dot notation;
student=Student.objects.filter(pk=...)
to refer to your required fields:
student.last_name, student.course.course_title
Besides, if I understood your models, you could get some incongruence... what if the value stored in course_parent_id in Students model is different from the value stored in parent_id in Courses model? maybe the first one is redundant.
To query a field from a related object use a double underscore. So you could do
Student.objects.filter(**kwargs).values('first_name', 'last_name', 'course__course_name')

DRF - filter across 2 models

I'm working with a legacy database where I have a serializer setup on Table A like so -
class TblapplicationsSerializer(serializers.ModelSerializer):
class Meta:
model = Tblapplications
fields = ('applicationid', 'applicationname', 'description', 'drtierid', 'saglink', 'supportinstructions',
'defaultincidentpriorityid', 'applicationorigintypeid', 'installationtypeid', 'comments',
'lastmodifieddate', 'lastmodifiedby', 'assetstatusid', 'recordownerid', 'adl_app')
depth = 2
I'm using a standard filter -
class TblapplicationsFilter(django_filters.FilterSet):
name = django_filters.CharFilter(name="applicationname", lookup_type="exact")
env = django_filters.CharFilter(name="adl_app__environmentid__domain")
class Meta:
model = Tblapplications
fields = ['applicationname', 'name', 'env']
Here's where it goes sideways. What I want to be able to do is filter on my URL like /api/applications/?name=xxx&env=DEV. It would then return the application and any databases that are linked with the environment of DEV. The name was understandably easy, but the only was I figured out the environment was to make the api point for applications touch the middle table that links the two but it returns multiple values because it's grabbing each time application is referenced with a separate database.
I've updated the Serializer and Filter based on comments given and the serializer, without the &env=DEV returns all the appropriate data (domain is nested in a reverse relationship). I then want my filter to filter the results based on that. Which means that it needs to somehow know to limit the results on the reverse relationship to only what's provided from the nested value.
If you see my models -
class Tblapplicationdatabaselinks(models.Model):
id = models.AutoField(db_column='ID', primary_key=True)
applicationid = models.ForeignKey('Tblapplications', db_column='applicationId', to_field='applicationid',
related_name='adl_app')
dbid = models.ForeignKey('Tbldatabases', db_column='dbId', to_field='id', related_name='adl_db')
environmentid = models.ForeignKey('Tbldomaincodes', db_column='environmentId', to_field='id',
related_name='adl_envlink')
comments = models.TextField(blank=True)
lastmodifieddate = models.DateTimeField(db_column='lastModifiedDate', blank=True, null=True)
lastmodifiedby = models.CharField(db_column='lastModifiedBy', max_length=255, blank=True)
# upsize_ts = models.TextField(blank=True) # This field type is a guess.
class Meta:
managed = False
db_table = 'tblApplicationDatabaseLinks'
class Tblapplications(models.Model):
applicationid = models.AutoField(db_column='applicationId', primary_key=True)
applicationname = models.CharField(db_column='applicationName', max_length=255)
description = models.TextField(blank=True)
drtierid = models.ForeignKey(Tbldomaincodes, db_column='drTierID', blank=True, null=True, to_field='id',
related_name='app_drtier')
saglink = models.TextField(db_column='sagLink', blank=True)
supportinstructions = models.TextField(db_column='supportInstructions', blank=True)
defaultincidentpriorityid = models.IntegerField(db_column='defaultIncidentPriorityId', blank=True, null=True)
applicationorigintypeid = models.IntegerField(db_column='applicationOriginTypeId')
installationtypeid = models.ForeignKey(Tbldomaincodes, db_column='installationTypeId', to_field='id',
related_name='app_insttype')
comments = models.TextField(blank=True)
assetstatusid = models.ForeignKey(Tbldomaincodes, db_column='assetStatusId', to_field='id',
related_name='app_status')
recordownerid = models.ForeignKey(Tblusergroups, db_column='recordOwnerId', blank=True, null=True,
to_field='groupid', related_name='app_owner')
lastmodifieddate = models.DateTimeField(db_column='lastModifiedDate', blank=True, null=True)
lastmodifiedby = models.CharField(db_column='lastModifiedBy', max_length=255, blank=True)
# upsize_ts = models.TextField(blank=True) # This field type is a guess.
class Meta:
managed = False
db_table = 'tblApplications'
class Tbldatabases(models.Model):
dbid = models.AutoField(db_column='dbId', primary_key=True)
dbname = models.CharField(db_column='dbName', max_length=255)
serverid = models.ForeignKey('Tblservers', db_column='serverId', to_field='serverid', related_name='db_serv')
servicename = models.CharField(db_column='serviceName', max_length=255, blank=True)
dbtypeid = models.IntegerField(db_column='dbTypeId', blank=True, null=True)
inceptiondate = models.DateTimeField(db_column='inceptionDate', blank=True, null=True)
comments = models.TextField(blank=True)
assetstatusid = models.IntegerField(db_column='assetStatusId')
recordownerid = models.IntegerField(db_column='recordOwnerId', blank=True, null=True)
lastmodifieddate = models.DateTimeField(db_column='lastModifiedDate', blank=True, null=True)
lastmodifiedby = models.CharField(db_column='lastModifiedBy', max_length=255, blank=True)
# upsize_ts = models.TextField(blank=True) # This field type is a guess.
class Meta:
managed = False
db_table = 'tblDatabases'
class Tbldomaincodes(models.Model):
id = models.IntegerField(db_column='ID', primary_key=True)
domain = models.CharField(primary_key=True, max_length=255)
displayname = models.CharField(db_column='displayName', primary_key=True, max_length=255)
displayorder = models.IntegerField(db_column='displayOrder', blank=True, null=True)
comments = models.TextField(blank=True)
lastmodifieddate = models.DateTimeField(db_column='lastModifiedDate', blank=True, null=True)
lastmodifiedby = models.CharField(db_column='lastModifiedBy', max_length=255, blank=True)
# upsize_ts = models.TextField(blank=True) # This field type is a guess.
class Meta:
managed = False
db_table = 'tblDomainCodes'
Extend your filter set and reference the field in the other model:
class TblapplicationsFilter(django_filters.FilterSet):
name = django_filters.CharFilter(name="applicationname", lookup_type="exact")
env = django_filters.CharFilter(name="environmentid__name")
# ^^^^^^^^^^^^^^^^^^^
class Meta:
model = Tblapplications
fields = ['applicationname', 'name', 'env']
Also, you may wish to name your ForeignKey fields without the id suffix, which is the Django convention. In Django, when you access Tblapplications.environmentid, it is normally a model instance, not the actual id integer itself.

Pulling Data From Multiple Tables in Django

I'm kind of new to Django and am having some trouble pulling from existing tables. I'm trying to pull data from columns on multiple joined tables. I did find a solution, but it feels a bit like cheating and am wondering if my method below is considered proper or not.
class Sig(models.Model):
sig_id = models.IntegerField(primary_key=True)
parent = models.ForeignKey('self')
state = models.CharField(max_length=2, db_column='state')
release_id = models.SmallIntegerField(choices=releaseChoices)
name = models.CharField(max_length=255)
address = models.CharField(max_length=255, blank=True)
city = models.CharField(max_length=255, blank=True)
zip = models.CharField(max_length=10, blank=True)
phone1 = models.CharField(max_length=255, blank=True)
fax = models.CharField(max_length=255, blank=True)
email = models.EmailField(max_length=255, blank=True)
url = models.URLField(max_length=255, blank=True)
description = models.TextField(blank=True)
contactname = models.CharField(max_length=255, blank=True)
phone2 = models.CharField(max_length=255, blank=True)
ratinggroup = models.BooleanField()
state_id = models.ForeignKey(State, db_column='state_id')
usesigrating = models.BooleanField()
major = models.BooleanField()
class Meta:
db_table = u'sig'
class SigCategory(models.Model):
sig_category_id = models.IntegerField(primary_key=True)
sig = models.ForeignKey(Sig, related_name='sigcategory')
category = models.ForeignKey(Category)
class Meta:
db_table = u'sig_category'
class Category(models.Model):
category_id = models.SmallIntegerField(primary_key=True)
name = models.CharField(max_length=255)
release_id = models.SmallIntegerField()
class Meta:
db_table = u'category'
Then, this was my solution, which works, but doesn't quite feel right:
sigs = Sig.objects.only('sig_id', 'name').extra(
select = {
'category': 'category.name',
},
).filter(
sigcategory__category__category_id = categoryId,
state_id = stateId
).order_by('sigcategory__category__name', 'name')
Now since the items in filter() join the sigcategory and category models, I was able to pull category.name out by using extra(). Is this a proper way of doing this? What if I did not have the reference in filter() and the join did not take place?
SigCategory has a ForeignKey pointing at Category, so you can always get from the SigCategory to the Category simply by doing mysigcategory.category (where mysigcategory is your instance of SigCategory.
If you haven't previously accessed that relationship from that instance, doing it here will cause an extra database lookup - if you're concerned about db efficiency, look into select_related.

Categories