Django - having more than one foreignkey in the same model - python

models.py
class City(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=35)
countrycode = models.CharField(max_length=3)
district = models.CharField(max_length=200)
population = models.IntegerField(default='0')
class Country(models.Model):
code = models.CharField(primary_key=True, max_length=3)
name = models.CharField(max_length=52)
continent = models.CharField(max_length=50)
region = models.CharField(max_length=26)
surfacearea = models.FloatField()
indepyear = models.SmallIntegerField(blank=True, null=True)
population = models.IntegerField()
lifeexpectancy = models.FloatField(blank=True, null=True)
gnp = models.FloatField(blank=True, null=True)
gnpold = models.FloatField(blank=True, null=True)
localname = models.CharField(max_length=45)
governmentform = models.CharField(max_length=45)
headofstate = models.CharField(max_length=60, blank=True, null=True)
capital = models.IntegerField(blank=True, null=True)
code2 = models.CharField(max_length=2)
SQL For the models
for City
INSERT INTO city VALUES (3955,'Sunnyvale','USA','California',131760);
for Country
INSERT INTO country VALUES ('BHS','Bahamas','North America','Caribbean',13878.00,1973,307000,71.1,3527.00,3347.00,'The Bahamas','Constitutional Monarchy','Elisabeth II',148,'BS');
Question 1
In the above mentioned models how can i relate code in the Country.code to City.countrycode, i am not able to do so because Country model is declared after the City model.
Question 2
And how to link the Country.capital in the Country model which is a integer that relates to City.name.
Note
I am converting a .sql file with InnoDB Engine to Postgresql.

looks like you need declare foreign key related by string
class City(models.Model):
name = models.CharField(max_length=35)
countrycode = models.ForeignKey('Country', blank=True, null=True)
class Country(models.Model):
code = models.CharField(primary_key=True, max_length=3)
name = models.CharField(max_length=52)
capital = models.ForeignKey('Country', blank=True, null=True)

Related

how to store user data from user model inside a database table in django

I have a Buyer table in mysql database and I want to take the username , email, password from User model ( default django model ) and store it inside Buyer table,
Buyer model in models.py:
class Buyer(models.Model):
row_id = models.AutoField(primary_key=True)
user_name = models.CharField(unique=True, max_length=50)
user_password = models.CharField(max_length=16)
first_name = models.CharField(max_length=50)
middle_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50)
email = models.CharField(unique=True, max_length=100)
home_phone = models.CharField(max_length=20, blank=True, null=True)
mobile_phone = models.CharField(unique=True, max_length=20)
personal_id = models.CharField(max_length=30, blank=True, null=True)
idtype_fk = models.ForeignKey('Idtype', models.DO_NOTHING, db_column='idType_FK', blank=True, null=True) # Field name made lowercase.
personal_id_country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='personal_id_country_FK',related_name='personal_id_country_fk') # Field name made lowercase.
address_line_1 = models.CharField(db_column='address_Line_1', max_length=200) # Field name made lowercase.
address_line_2 = models.CharField(db_column='address_Line_2', max_length=200, blank=True, null=True) # Field name made lowercase.
p_o_box = models.CharField(max_length=20, blank=True, null=True)
city = models.CharField(max_length=50)
country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='country_FK' , related_name='country_fk') # Field name made lowercase.
gender_fk = models.ForeignKey('Gender', models.DO_NOTHING, db_column='gender_FK') # Field name made lowercase.
bdate = models.DateField()
def __str__(self):
return 'User: ' + self.user_name
class Meta:
managed = False
db_table = 'buyer'
and after the registration User/Buyer can add more information such as first name , mobile phone etc.. in the profile page
As Willem van Onsem mentioned, use a ForeignKey in your Buyer model to reference to the user object:
class Buyer(models.Model):
#other stuff
user_fk = models.ForeignKey(User, on_delete=models.SET_NULL)
#other stuff
Or, if every Buyer is just one User and every User is just one Buyer, use a OneToOneField instead of a ForeignKey.
If you would then want to access the username/email/password you can use a query like this:
buyer = Buyer.objects.all().first()
buyer_email = buyer.user_fk.email

django - Runpython function to turn charfield into foreignkey

I've been strugglin to relate a csv imported data model with a spatial data model based on a CharField.
I've created both models and now im trying to transfer the data from one field to a new one to be the ForeignKey field. I made a Runpython funtion to apply on the migration but it goives the an error:
ValueError: Cannot assign "'921-5'":
"D2015ccccccc.rol_fk" must be a "D_Base_Roles" instance.
Here are the models:
class D_Base_Roles(models.Model):
predio = models.CharField(max_length=254)
dest = models.CharField(max_length=254)
dir = models.CharField(max_length=254)
rol = models.CharField(primary_key=True, max_length=254)
vlr_tot = models.FloatField()
ub_x2 = models.FloatField()
ub_y2 = models.FloatField()
instrum = models.CharField(max_length=254)
codzona = models.CharField(max_length=254)
nomzona = models.CharField(max_length=254)
geom = models.MultiPointField(srid=32719)
def __str__(self):
return str(self.rol)
class Meta():
verbose_name_plural = "Roles"
class D2015ccccccc(models.Model):
id = models.CharField(primary_key=True, max_length=80)
nombre_archivo = models.CharField(max_length=180, blank=True, null=True)
derechos = models.CharField(max_length=120, blank=True, null=True)
dir_calle = models.CharField(max_length=120, blank=True, null=True)
dir_numero = models.CharField(max_length=120, blank=True, null=True)
fecha_certificado = models.CharField(max_length=50, blank=True, null=True)
numero_certificado = models.CharField(max_length=50, blank=True, null=True)
numero_solicitud = models.CharField(max_length=50, blank=True, null=True)
rol_sii = models.CharField(max_length=50, blank=True, null=True)
zona_prc = models.CharField(max_length=120, blank=True, null=True)
##NEW EMPTY FOREIGNKEY FIELD
rol_fk = models.ForeignKey(D_Base_Roles, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return str(self.numero_certificado)
class Meta:
managed = True
#db_table = 'domperm2015cip'
verbose_name_plural = "2015 Certificados Informaciones Previas"
ordering = ['numero_certificado']
The Runpython function:
def pop_rol(apps, schema_editor):
roles = apps.get_model('b_dom_edificacion', 'D2015ccccccc')
for r in roles.objects.all():
rol = roles
r.rol_fk = r.rol_sii
r.save()
D_Base_Roles.rol values are all unique, and 921-5 is one of those values.
What am I missing?
You probably need to assign an object, not a string. Change the line
r.rol_fk = r.rol_sii
to
r.rol_fk = D_Base_Roles.objects.get(rol=r.rol_sii)
Maybe adjust to whatever the correct field for looking up D_Base_Roles instances is.
Note: this will make a database query for every iteration of the for-loop

Django 1.11 not recognising Foreign Key model assignments

I am having an issue with 2 Foreign Key assignments in my django model. See models.py below:
from django.db import models
from django.contrib.auth.models import User
class userData(models.Model):
user = models.ForeignKey(User)
house = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=True, null=True)
street = models.CharField(max_length=150)
state = models.CharField(max_length=100)
postcode = models.CharField(max_length=20)
country = models.CharField(max_length=100)
telephone = models.CharField(max_length=20)
subscription = models.IntegerField(default=0)
active = models.IntegerField(default=0)
class area(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class country(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class city(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class foodType(models.Model):
food_type_name = models.CharField(max_length=100)
class restaurant(models.Model):
restaurant_name = models.CharField(max_length=100)
food_type = models.ForeignKey(foodType)
area = models.ForeignKey(area)
country = models.ForeignKey(country)
city = models.ForeignKey(city)
date_added = models.DateField()
main_image = models.ImageField(blank=True, null=True)
website = models.URLField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
featured = models.IntegerField(default=0)
class restaurantFeature(models.Model):
feature_name = models.CharField(max_length=100)
restaurant_id = models.ForeignKey(restaurant)
Django Foreign Key not working correctly
The image shows the Country and City, not showing correctly, like the FoodType and Area does. Theses show with the + buttons for adding, the mysql database is showing the key next to the fields. I have also tried renaming country and City adding Location after, thinking it could be something with these names.
Appreciate any help with this one.
You're having this issue because you need to reference ALL the models inside the admin.py. Django admin doesn't know what you're referencing.

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')

Django model query

I have question about Django query models. I know how to write simple query, but Im not familiar with LEFT JOIN on two tables. So can you give me some advice on his query for better understanding DJango ORM.
query
select
count(ips.category_id_id) as how_many,
ic.name
from
izibizi_category ic
left join
izibizi_product_service ips
on
ips.category_id_id = ic.id
where ic.type_id_id = 1
group by ic.name, ips.category_id_id
From this query I get results:
How many | name
0;"fghjjh"
0;"Papir"
0;"asdasdas"
0;"hhhh"
0;"Boljka"
0;"ako"
0;"asd"
0;"Čokoladne pahuljice"
0;"Mobitel"
2;"Čokolada"
And I have also try with his Django query:
a = Category.objects.all().annotate(Count('id__category',distinct=True)).filter(type_id=1)
But no results.
My models:
models.py
class Category(models.Model):
id = models.AutoField(primary_key=True)
type_id = models.ForeignKey('CategoryType')
name = models.CharField(max_length=255)
def __str__(self):
return str(self.name)
class Product_service(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, blank=True, null=True)
selling_price = models.DecimalField(decimal_places=5, max_digits=255, blank=True, null=True)
purchase_price = models.DecimalField(decimal_places=5, max_digits=255, blank=True, null=True)
description = models.CharField(max_length=255, blank=True, null=True)
image = models.FileField(upload_to="/", blank=True, null=True)
product_code = models.CharField(max_length=255, blank=True, null=True)
product_code_supplier = models.CharField(max_length=255, blank=True, null=True)
product_code_buyer = models.CharField(max_length=255, blank=True, null=True)
min_unit_state = models.CharField(max_length=255, blank=True, null=True)
state = models.CharField(max_length=255, blank=True, null=True)
vat_id = models.ForeignKey('VatRate')
unit_id = models.ForeignKey('Units')
category_id = models.ForeignKey('Category')
If you culd help me on this problem.
You should add a related name on the category_id field like:
category_id = models.ForeignKey('Category', related_name="product_services")
so that in your query you can do:
a = Category.objects.all().annotate(Count('product_services',distinct=True)).filter(type_id=1)
and then you can access the individual counts as:
a[0].product_services__count

Categories