Django queryset all fields of foreign key - django

I am looking for an elegant and efficient way to pull data out of two tables that have a one-to-one relationship.
Here are my models:
class Contact(models.Model):
name = models.CharField(max_length=100)
country = models.CharField(max_length=100)
status = models.BooleanField()
class ContactDetails(models.Model):
contact_name = models.ForeignKey(Contact)
contact_phone = models.CharField(max_length=100)
contact_fax = models.CharField(max_length=100)
and my view:
def showContact(request):
contacts = ContactDetails.objects.select_related('name').all()
print contacts.values() // debugging in console
return render(request, 'contacts/listContacts.html', { 'contacts': contacts } )
What I try to achieve is a list in my template like:
name, contact_phone, contact_fax, country, status
This again is something that must be so super simple, but I just stuck since a while with this now.
Thanks!

Fields on related models can be accessed via their given relation field.
if somedetails.contact_name.status:
print somedetails.contact_name.country

Related

Django Model advance Foreignkey Relation

I have a Django model which has relationship with user model. Where user are assigned to groups. especially "Admin", "Teacher","Student". So I want to make a foreign key relationship in such a way that it will show only The users that have been assigned to Teacher groups for Teacher_details model, And Similar for Student_Details Model. I have made the models Teacher_Details , Student_Details and established foreign key relation with User model. But the problem is that its showing all the user when I am filling Student_Details or Teacher_Details. Hope you got my problem.
I am hoping positive response.
The code looks like this:
class Student_Details(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(default='none', upload_to='img/')
details_updated = models.DateTimeField(auto_now_add=True)
address = models.CharField(max_length=150)
admission_date = models.DateField()
previous_college = models.CharField(max_length=150)
course_enrolled = models.ForeignKey(ModelUniversity,on_delete=models.CASCADE)
semester = models.CharField(max_length=20,choices=semester,default=None)
def __str__(self):
return self.user.first_name
class Teacher_Details(models.Model):
address = models.CharField(max_length=150)
image = models.ImageField(default='none', upload_to='img/')
details_updated = models.DateTimeField(auto_now_add=True)
subject_taught = models.ManyToManyField(to='Student.stu_subject')
user = models.OneToOneField(User,on_delete=models.CASCADE)
def __str__(self):
return self.user.first_name
def subject_teacher_teaches(self):
return [str(s) for s in self.subject_taught.all()]
Since both models have a user_id reference, you could use that info to search both models based on the request and fetch the necessary instance. Make a view which checks the user_id in the request, search both models and return the results (I assume a user cannot belong to both groups...)

Need to Fetch specific foreign key object product from database in Django

Hi everyone I am new at Django and working on e-commerce site. I create a model name category and pass it to model shop by using foreign key. In Category model I have category Sale and i want to fetch all products that have category sale in my landing page and rest of us in shop page. Any one please help me how I do it?
My model.py code is:
class category(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class shop(models.Model):
s_id = models.AutoField(primary_key=True)
s_name = models.CharField(max_length=50)
s_category = models.ForeignKey(category, on_delete= models.CASCADE)
s_artical_no = models.IntegerField(default=0)
View.py:
def index(request):
prod = shop.objects.get(s_category = 4)
params = {'prod': prod}
return render(request, "main/index.html", params )
Use related_name to accomplish this
class shop(models.Model):
s_category = models.ForeignKey(category, on_delete= models.CASCADE, related_name='shop_list')
In views.py
def index(request):
specific_category = category.objects.get(id=4)
prod = category.shop_list.all() #use related_name here
params = {'prod': prod}
return render(request, "main/index.html", params )
Hint: your classes names should follow the UpperCaseCamelCase convention so it should be Shop, Category
s_category is a category instance, you can't pass a category id. First get the category object for "Sale" i.e.
sale_category = category.objects.get(pk=4)
then simply use
prod = sale_category.shop_set.all()
As a side note, try to use PEP-8 compliant class names. The way you name your classes is confusing

Syntax to reverse-query a cached queryset

I have the following 3 models related by Foreign Key as following:
class Seller(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Genre(models.Model):
seller= models.ForeignKey(Seller, related_name="genre", on_delete=models.CASCADE)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Book(models.Model):
genre= models.ForeignKey(Genre, related_name="book", on_delete=models.CASCADE)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
And I want to retrieve the whole 3 tables in one database query, by querying the Seller objects, as following:
sellers = Seller.objects.select_related('genre', 'book').all().values('name')
seller_df = pd.DataFrame(list(sellers))
What is the syntax to filter for books carried by a particular seller, without hitting the database again (by utilizing either the Seller queryset or the pandas seller_df)
seller1 = seller_df ['name'].iloc[0]
seller1_books = Book.objects.filter(...)
seller_last = seller_df ['name'].iloc[-1]
seller_last_books = Book.objects.filter(...)
I dont know so mach about caching but I know something that you like:
We use select_related when the object is single like onetoone or fk.
.
for many to many or reverse fk like your example use prefetch_related

how to set django model field value based on value of other field in the different model

I am extremely new to django. I want to add field values based on other field value of other class. How can do this? can I do it with django custom actions?
please help
Sorry for my bad english
In model.py
from django.db import models
# Create your models here.
class Teachers(models.Model):
teacher_name = models.CharField(max_length=255)
def __str__(self):
return self.teacher_name
class Students(models.Model):
teacher = models.ForeignKey(Teachers,related_name="students_teachers")
student_rollno = models.IntegerField()
student_name = models.CharField(max_length=255)
student_last_name = models.CharField(max_length=255)
def __str__(self):
return self.student_name
class Subjects(models.Model):
teacher = models.ForeignKey(Teachers,related_name="subjects_teachers")
student = models.ForeignKey(Students,related_name="subjects_students")
book_name = models.CharField(max_length=255)
book_description = models.CharField(max_length=255)
book_author = models.CharField(max_length=255)
def __str__(self):
return self.book_name
Here, i create three models ('Teachers, Students, Subjects')
In Students class i use Teachers class as foreign key.
and in Subjects i use Teachers and Students as foreign key.
In admin section :
in Subjects section Teachers, and Studetns dropdown is shown.
Hope its help you :-)
Something like this below..
from App1 import Model1
from App2 import Model2
q1 = Model1.objects.filter(pk=something)
if q1:
field1 = q1[0].field1
q2 = Model1.objects.filter(pk=something)
if field1 =='something':
if q2:
q2[0].field2 == 'something'
q2[0].save()
Note: (pk - primary key)
Model1.objects.get(somefield=something) will throw error if there is no results or more than one results
Model1.objects.filter(somefield=something) will not throw errors if there is no results

Model with Foreign keys not behaving as expected - Django

I have a model with two foreign keys to create many to many relationship - I am not using many to many field in Django
class Story(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.title
class Category(models.Model):
categoryText = models.CharField(max_length=50)
parentCat = models.ForeignKey('self',null=True,blank=True)
def __unicode__(self):
return self.categoryText
class StoryCat(models.Model):
story = models.ForeignKey(Poll,null=True,blank=True)
category = models.ForeignKey(Category,null=True,blank=True)
def __unicode__(self):
return self.story
I would like to query for a category like 'short', and retrieve all the unique keys to all stories returned.
>>>c=Category(categoryText='short')
>>>s=StoryCat(category=c)
when I try this I get errors "AttributeError: 'NoneType' object has no attribute 'title'. How can I do this?
I would like to query for a category like 'short', and retrieve all the unique keys to all stories returned.
c=Category.objects.get(categoryText='short')
story_ids = StoryCat.objects.filter(category=c).values_list('story')
And about your models:
Category name should probably be unique. And declare your many-to-many relation.
class Category(models.Model):
categoryText = models.CharField(max_length=50, unique=True)
stories = models.ManyToManyField(Story, through='StoryCat')
...
It makes no sense for intermediary table FK fields to be nullable. Also I assume the same story should not be added to the same category twice, so set a unique constraint.
class StoryCat(models.Model):
story = models.ForeignKey(Poll)
category = models.ForeignKey(Category)
class Meta:
unique_together = ('story', 'category')
The lines you're executing in the interpreter are not queries - they are instantiating new objects (but not saving them).
Presumably you meant this:
>>>c=Category.objects.get(categoryText='short')
>>>s=StoryCat.objects.get(category=c)