Django 1.11 not recognising Foreign Key model assignments - python

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.

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

How to create a view for a nested serializer with foreign keys in django rest framework?

I got this code, but I can't find a way to create a view that retrieve the allergies a patient has.
class Patient(models.Model):
user = models.OneToOneField(User, related_name='patient', on_delete=models.CASCADE)
id_type = models.CharField(max_length=300)
id_number = models.CharField(max_length=300)
creation_date = models.DateField(default=datetime.date.today)
class Allergie(models.Model):
name = models.CharField(max_length=300, default="X")
class PatientAllergies(models.Model):
patient = models.ForeignKey(Patient, related_name="patient_allergies", on_delete=models.CASCADE)
allergie = models.ForeignKey(Allergie, on_delete=models.CASCADE, null=True)
professional_contract = models.ForeignKey(ProfessionalContract, null=True ,on_delete=models.CASCADE)
You can span a ManyToManyField relation over your PatientAllergies model that acts as a junction table:
class Patient(models.Model):
user = models.OneToOneField(User, related_name='patient', on_delete=models.CASCADE)
id_type = models.CharField(max_length=300)
id_number = models.CharField(max_length=300)
creation_date = models.DateField(auto_now_add=True)
allergies = models.ManyToManyField(
'Allergie',
through='PatientAllergies'
)
# …
You can then for a Patient object p with:
p.allergies.all()
An alternative is to filter the Allergie objects with:
Allergie.objects.filter(patientallergies__patient=p)
or with the ManyToManyField:
Allergie.objects.filter(patient=p)

How to link address model to views

I'm trying to create an address form with multiple address, where the user can choose home or shipping address. I have the current model:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Address(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60, default="Miami")
state = models.CharField(max_length=30, default="Florida")
zipcode = models.CharField(max_length=5, default="33165")
country = models.CharField(max_length=50)
class Meta:
verbose_name = 'Address'
verbose_name_plural = 'Address'
def __str__(self):
return self.name
So I was wondering if that's correct.
Anyway, I was wondering how with the current model I can create a view so I can have the address form. Using a normal model would be "easy" but how can I do it using the through option in the model?
Could someone lend me a hand please?
Thank you
use a foreign key to point to your address model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
nick_name = models.CharField('Nick name', max_length=30, blank=True, default='')
bio = models.TextField(max_length=500, blank=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
addresses = models.ForeignKey(Address) # <-- fix here
Hope this helps!
You should declare ForeignKey with '<app>.<model>' format:
class AddressType(models.Model):
address = models.ForeignKey('yourapp.Address', on_delete=models.CASCADE)
profile = models.ForeignKey('yourapp.Profile', on_delete=models.CASCADE)
or directly give the class:
address = models.ForeignKey(Address, on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
Both of the other answers were incorrect, I ended up modifying everything and also creating a new model, here it is:
class Address(models.Model):
name = models.CharField(max_length=100, blank=False)
address1 = models.CharField("Address lines 1", max_length=128)
address2 = models.CharField("Address lines 2", max_length=128, blank=True)
city = models.CharField("City", max_length=64)
# state = USStateField("State", default='FL')
state = models.CharField("State", max_length=128, default='FL')
zipcode = models.CharField("Zipcode", max_length=5)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=False)
class Meta:
verbose_name_plural = 'Address'
def __str__(self):
return self.name

Django - having more than one foreignkey in the same model

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)

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

Categories