Django Model ForeignKey 2 - django

I dont understand how I can "import"(I dont know the right terminology, so please dont crucify me on this) a Foreignkey from 1 model class to a another:
e.g.
class1 (models.Model):
variable1 = models.CharField()
variable2 = models.CharField()
class2 (models.Model):
variable3 = models.CharField()
variable4 = class1.variable1 "imported" from class1
So now I have all the data from variable1 from class1 available in class2.
I assume this would be accomplished by a ForeignKey.
If I take the example of the official Django documentation (see below), I dont get my answer because:
Why does it only mention the other model and not the variable I create from it.
This would be for a future model, where I dont know the fields yet. But i know the fields already. Again no variable, just the model.
This would be what I am looking for. But this is "imported" from another app. But with me it is in the same app.
ad 1.
class ForeignKey(othermodel[, **options])ΒΆ
ad 2.
class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...
class Manufacturer(models.Model):
# ...
ad 3.
class Car(models.Model):
manufacturer = models.ForeignKey('production.Manufacturer')
Thanks!

If I understand your question correctly.
You are establishing the relationship to the whole model with a foreign key, not just one field, so you will have access to all the fields, even if you only want one.
variable4 = models.ForeignKey(class1)
now you can say variable4.variable1 or variable4__variable2 in a queryset.
Re point 2 - use variable4 = models.ForeignKey('class1') if class1 not already defined
Re point 3 - no need to add application if model in the current application.

Related

How to expand application to work with multiple users and seasons

Let's say that I have created an app for a school with several models (e.g. Student, Teacher, Course, Attendance, Grade, Timetable, Payments etc).
It's working great for the current year. But now I want to expand my application, so that several schools can use it and it can store data of (mostly) independent seasons/years.
The first solution that comes to my mind, is to add 2 extra models (1)school=user and (2)season=year. And then add ForeignKeys from (almost) ALL my models to both of these (school, season).
(Maybe I could add a third model named SchoolSeason, with just these 2 fields and use this as FK to all my fields.)
Is there a more elegant solution?
Edit: a drawback to this solution would be that the models (e.g. Students) will share their auto-incremented ID with other schools.
Hard to tell without your current models but I would to the same by adding to 2 extra models. But no need to add both of them to all of your models : only Season is needed if you link Season to School.
class School(models.Model):
name = models.CharField(...)
class Season(models.Model):
school = models.ForeignKey(School)
name = models.CharField(...)
other_fields...
Each Season is linked to a School. Then, you can add the Foreign Key to all of your models.
About your problem in the edit, you are right, it would be a problem. You should not use auto-incremented key but UUid.
Finally, it would look like :
class BaseSeasonModel(models.Model):
uid = models.UUIDField(
primary_key=True,
default=uuid_lib.uuid4,
editable=False,
)
season = models.ForeignKey(Season)
class Meta:
abstract = True
And all of your models would inherit from it :
class Student(BaseSeasonModel):
...

Django many-to-many lookup from different models

I have some models that represents some companies and their structure. Also all models can generate some Notifications (Notes). User can see own Notes, and, of course, can't see others.
class Note(models.Model):
text = models.CharField(...)
class Company(models.Model):
user = models.ForeignKey(User)
note = models.ManyToManyField(Note, blank='True', null='True')
class Department(models.Model):
company = models.ForeignKey(Company)
note = models.ManyToManyField(Note, blank='True', null='True')
class Worker(models.Model):
department = models.ForeignKey(Department)
note = models.ManyToManyField(Note, blank='True', null='True')
class Document(models.Model)
company = models.ForeignKey(Company)
note = models.ManyToManyField(Note, blank='True', null='True')
The question is how I can collect all Notes for particular user to show them?
I can do:
Note.objects.filter(worker__company__user=2)
But its only for Notes that was generated by Workers. What about another? I can try hardcoded all existing models, but if do so dozen of kittens will die!
I also tried to use backward lookups but got "do not support nested lookups". May be I did something wrong.
EDIT:
As I mentioned above I know how to do this by enumerating all models (Company, Worker, etc. ). But if I will create a new model (in another App for example) that also can generate Notes, I have to change code in the View in another App, and that's not good.
You can get the Notes of a user by using the following query:
For example let us think that a user's id is 1 and we want to keep it in variable x so that we can use it in query. So the code will be like this:
>>x = 1
>>Note.objects.filter(Q(**{'%s_id' % 'worker__department__company__user' : x})|Q(**{'%s_id' % 'document__company__user' : x})|Q(**{'%s_id' % 'company__user' : x})|Q(**{'%s_id' % 'department__company__user' : x})).distinct()
Here I am running OR operation using Q and distinct() at the end of the query to remove duplicates.
EDIT:
As I mentioned above I know how to do this by enumerating all models
(Company, Worker, etc. ). But if I will create a new model (in another
App for example) that also can generate Notes, I have to change code
in the View in another App, and that's not good.
In my opinion, if you write another model, how are you suppose to get the notes from that model without adding new query? Here each class (ie. Department, Worker) are separately connected to Company and each of the classes has its own m2m relation with Note and there is no straight connection to User with Note's of other classes(except Company). Another way could be using through but for that you have change the existing model definitions.
Another Solution:
As you have mentioned in comments, you are willing to change the model structure if it makes your query easier, then you can try the following solution:
class BaseModel(models.Model):
user = models.Foreignkey(User)
note = models.ManyToManyField(Note)
reports_to = models.ForeignKey('self', null=True, default=None)
class Company(BaseModel):
class Meta:
proxy = True
class Document(BaseModel):
class Meta:
proxy = True
#And so on.....
Advantages: No need to create separate table for document/company etc.
object creation:
>>c= Company.objects.create(user_id=1)
>>c.note.add(Note.objects.create(text='Hello'))
>>d = Document.objects.create(user_id=1, related_to=c)
>>d.note.add(Note.objects.create(text='Hello World'))

Weak Entities in Django

Can somebody please explain me how to represent a weak entity relationship in django?
i searched for it in django's documentation, but couldn't find. I even searched on google and stackoverflow before posting a question here.
In case its not possible to represent a weak entity relationship, then please let me know what is the most appropriate alternative to it in django
Update:
I was developing an e-learning site, so there's a Course class with attributes like title, description, creator, etc. and I want to add a weak entity called "Week" (to store week-wise content for the course) which would be attached to this strong entity called Course, and I wanted course_id from Course class and week_no from Week class to act as a primary key for each entry in Week class
Well, let's take this example from wikipedia
You have a class Order and a class Product.
You'd then have a class OrderItem which would be the weak entity.
class Order(models.Model):
some_attributes
class Product(models.Model):
some_other_attributes
class OrderItem(models.Model)
order = models.ForeignKey(Order)
product = models.ForeignKey(Product)
other_attributes
class Meta:
unique_together = (order, product)
the unique_together meta property would make sure each OrderItem's won't have more than a database entry where both these values are repeated.
I reckon this may not match exactly what it you're looking for, but it may be a start. If you provide more details on what's you're trying to accomplish, perhabs I can help with some table tweaking or even query examples for getting data using this approach.
edit:
You are correct, there is no such field as weaker entity field. My sugestion is that you treat the week model as you would any other. And link it to the Course model, like so:
class Course(models.Model):
title = models.CharField()
description = models.CharField()
etc..
class CourseWeek(models.Model):
course = models.ForeignKey(Course)
week_number = models.IntegerField()
topic = models.CharField()
slideshow = models.FileField()
class Meta:
unique_together = ('course' , 'week_number')
Hope this helps :)

django model with foreign key to one of two possible models

I have a two models that are similar, but not exactly the same. Here's the best abstraction of the problem that I can come up with.
class Cat(models.Model):
name = models.TextField()
breed = models.TextField()
class Dog(models.Model):
name = models.TextField()
color = models.TextField()
And now I need to make another model like this.
class Pet(models.Model):
favoriteFood = models.TextField()
isCat = models.BooleanField()
animal = models.ForeignKey(?????????)
My problem is that the animal field of the Pet model is going to be a foreign key to either the Cat or the Dog model depending on the value of isCat. How can I do that?
Now, I know this is an unusual/awkward schema in the first place, but I wasn't involved in its creation and I can't change it. I just have to support it. I'm writing these models for an existing database.
You should see Generic relations.
Generic relations is a direct answer.
Another option for this use case is: django-polymorphic :)

Django Model ForeignKey

If I want to add a Foreignkey to a model from another class in the same model e.g.
class1 (models.Model):
variable1 = models.IntegerField()
class2 (models.Model):
variable2 = models.CharField()
foreignkey = models.Foreignkey(class1.variable1)
Is that possible?
Does that make sense as a programming move?
This ForeignKey would be an ID Number (like a primary key) that I would like to import to other classes as well.
# Manoj Govindan:
e.g.
class author(models.Model):
authorlabel= models.IntegerField() # With choices
...
class books(models.Model):
books=models.CharField()
foreignkey= models.Foreignkey(author.authorlabel)
So that I have that data available in that table(?)/model as well.
Thanks!
Perhaps this is what you are looking for:
models.ForeignKey(class1, to_field = 'variable1')
Relevant documentation is here.
This ForeignKey would be an ID Number (like a primary key) that I would like to import to other classes as well.
Not sure what you mean by this. Can you rephrase it and add an example?
Addition to Manoj Govindan's answer...
This ForeignKey would be an ID Number (like a primary key) that I would like to import to other classes as well.
No it do not have to be a number, it can be a string, a datetime value or something else... But it have to be unique.