I have a Postgres database with 3 tables with data and their models in Django. I do not have control over how these tables are filled. But I need to add relationships to them.
It would not be a problem for me in MsSQL, Oracle or MySql. But Im confused here.
class Keywords(models.Model):
id = models.AutoField(primary_key=True)
keyword = models.CharField(unique=True, max_length=250)
class Mapping(models.Model):
id = models.AutoField(primary_key=True)
keyword = models.CharField(max_length=250)
videoid = models.CharField(max_length=50)
class Video(models.Model):
videoid = models.CharField(primary_key=True, max_length=50)
In your model Mapping, which is used to relate with the models Keywords and Video, you can make changes like:
class Mapping(models.Model):
id = models.AutoField(primary_key=True)
keyword = models.ForeignKey(Keywords, on_delete=models.CASCADE)
videoid = models.ForeignKey(Video, on_delete=models.CASCADE)
You also don't need to define id for the model as Django itself creates a id field which is auto generated and primary key.
Use inspectdb in order to generate your models from your db tables.
$ ./manage.py inspectdb table1 table2 table3 >> models.py
Relation
class Video(models.Model):
#...
keywords = models.ManyToManyField(Keywords)
Then you can remove the Mapping model, the table for this relation is generated by Django.
If you want to keep the data of the already related instances, use the through key parameter for the ManyToManyField with the Mapping model.
Finally, I found a solution:
class Mapping(models.Model):
id = models.AutoField(primary_key=True)
video = models.ForeignKey(Videos, to_field='videoid', db_column='videoid', on_delete=models.DO_NOTHING,blank=False,null=True,)
keyword = models.ForeignKey(Keywords, to_field='keyword', db_column='keyword', on_delete=models.DO_NOTHING, blank=False, null=True,)
To add relations to existing tables with weird column names and type it is the best to use to_field and db_column. In this case, Django will not try to create standard id columns for relations.
Related
class Plans(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
plan_type = models.CharField(max_length=255)
class Order(models.Model):
id = models.IntegerField(primary_key=True)
selected_plan_id = models.IntegerField(primary_key=True)
Order's selected_plan_id is Plans's id.
Which model should I add a foreign key to? How?
First of all there are some bad ways to pointout:
two fields cannot be primary keys in a table
also django as default includes primary key id in every table, so no need to add id field.
You should be doing this way:
class Order(models.Model):
selected_plan_id = models.ForeignKey(Plans, on_delete=models.CASCADE)
The solution that you are looking for
class Order(models.Model):
id = models.IntegerField(primary_key=True)
selected_plan_id = models.ForeignKey(Plans, on_delete=models.CASCADE)
The purpose of using models.CASCADE is that when the referenced object is deleted, also delete the objects that have references to it.
Also i dont suggest to you add 'id' keyword to your property, django makes automatically it. If you add the 'id' keyword to end of the your property like this case, you gonna see the column called 'selected_plan_id_id' in your table.
class Order(models.Model):
id = models.IntegerField(primary_key=True)
selected_plan_id = models.IntegerField(primary_key=True)
Plain= models.ForeignKey(Plain)
Check the dependence of the table and after getting that made one key as foreign like in this one plain is not depend on the order. But the order depends on the plan.
This might be stupid question and I am sure that there is a basic query for this situation, but I don't seem to get a hang of it and Google turned out to be a miss for solution.
I have models:
Project, primary key=project_no;
Under project there are product_config models, primary key=id;
Under each product_config there is a pre_config model, primary key=product_id;
Under each pre_config there is a list of sub_config models, primary key=id;
Now I am loading a page for project details and I pass a project_no and make a query for all product_configs:
project.objects.get(project_no=project_no)
product_config.objects.filter(project_no=project_no)
Now I want to create a table for the list of sub_configs according to pre_config under product_config. In a shell I can query the list with:
config_assembly.objects.filter(product_id=product_id)
How I can pass the product_id of pre_config from my product_config to query all the sub_configs?
EDIT:
This is the basic structure of my models.
in project.models
class project(models.Model):
project_no = IntegerField('project no', primary_key=True)
class product_config(models.Model):
project_no = models.ForeignKey('project.project', on_delete=models.CASCADE, verbose_name='project no')
product_id = models.ForeignKey('product.pre_config', on_delete=models.CASCADE, verbose_name='product code')
in product.models
class pre_config(models.Model):
product_id = models.CharField('product code', max_length=30, unique=True, primary_key=True)
class sub_config(models.Model):
subproduct_id = models.CharField('subproduct code', max_length=20, unique=True, primary_key=True)
in assembly.models
class config_assembly(models.Model):
product_id = models.ForeignKey('product.pre_config', on_delete=models.CASCADE, verbose_name='product code')
subconfig_id = models.ForeignKey('product.sub_config', on_delete=models.CASCADE, verbose_name='subproduct code')
For your use case it sounds like you want to use the API for related objects.
If I'm understanding your question correctly, here's an example:
# Of course, you should handle cases when 0 or multiple product_configs
# match the query, and replace QUERY with an actual selector.
# This is the related pre_config's product_id
my_pre_config = product_config.objects.get(QUERY).product_id
assemblies = my_pre_config.config_assembly_set.all()
(I follow this standard for class names, so I may be mistaken about _set in your case. It could be configassembly_set.)
You can then iterate over assemblies to get the sub config of each config_assembly, like so: assembly.subconfig_id.
Also, for the purposes of readability, I would recommend renaming your foreign key fields from foo_id to something signifying the actual model that the foreign key points to. For example:
# models.py
class product_config(models.Model):
project = models.ForeignKey('project.project', on_delete=models.CASCADE)
Even though the database values will be IDs, in your code you probably want to reference my_product_config.project.project_no instead of my_product_config.project_no.project_no, which can get confusing and lead to mistaking model instances for raw ID values, and vice-versa.
So I Am Making A Shop Website I wanted to ask how do we add tables as a field? Do we use foreign key or something in Django I am using SQLite btw
https://i.stack.imgur.com/W1Y5H.png
I think you want to use model fields as table fields. Basically, you require ORM(Object-relational mapping). I am adding a basic model snippet below with a foreign key added.
class Collection(models.Model):
title = models.CharField(max_length=255)
# This for foreign key .The plus sign means that a reverse relation won't be created!
featured_product = models.ForeignKey('Product',on_delete=models.SET_NULL,null=True,related_name='+')
class Product(models.Model):
sku = models.CharField(max_length=10,primary_key=True)
title = models.CharField(max_length=255)
slug = models.SlugField(default='-')
description = models.TextField()
unit_price = models.DecimalField(max_digits=6,decimal_places=2)
inventory = models.IntegerField()
last_update = models.DateTimeField(auto_now=True)
collection = models.ForeignKey(Collection,on_delete=models.CASCADE)
I have two models:
class Amodel(models.Model):
name = models.CharField(max_length=8)
desc = models.CharField(max_length=256)
class Bmodel(models.Model):
name = models.CharField(max_length=8)
desc = models.CharField(max_length=256)
now I have another model:
class Cmodel(models.Model):
name = models.CharField(max_length=8)
f_model = models.ForeignKey(to='there I want to dynamic refers to Amodle or Bmodel when create the Cmodel instance')
I want the Cmodel's f_model is choosable when Create the Cmodel instance, whether this is possible?
This feature called generic relations. Here is the official documentation link generic-relations
By definition of foreign key you can not assign foreign key to one field with choices of model
A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
Instead you can proceed to create two fields as below:
class Cmodel(models.Model):
name = models.CharField(max_length=8)
f_a_model = models.ForeignKey(Amodel, blank=True, null=True, on_delete=models.CASCADE)
f_b_model = models.ForeignKey(Bmodel, blank=True, null=True, on_delete=models.CASCADE)
This way you can create two fields and you can keep it as null.
So If you wish to proceed for Cmodel instance with foreign key of a model you can add it to field f_a_model and keep f_b_model null and vice versa
You may follow example of using generic-relations from this link and the doc.
When you use generic relations you need to write your own custom field and method for serializer or form or anywhere you wish to user it.
I'm trying to figure out the Django ORM and I'm getting a little confused on the equivalent of a table join.
Assume I have the three models below, abbreviated for readability. "User" is the out-of-the-box Django user model, "AppUser" is a corresponding model for storing additional profile info like zip code, and "Group" is a collection of users (note that this group has nothing to do with authentication groups). Each AppUser has a one-to-one relationship with each User. Similarly, each AppUser also points to the Group of which that user is member (which could be None).
My task: given a group_id, generate a list of all the member emails.
I know that I can "traverse backward one-level" from Group to AppUser using .appuser_set.all() but I don't know how to go further to fetch the related User and its email without iterating through and doing it in a very DB heavy way like this:
appUser = AppUser.objects.get(user_id=request.user.id)
group = appUser.group
appUsers = group.appuser_set.all()
emails = []
for x in appUsers:
emails.append(x.user.email)
Alternatively I could write a raw SQL join to do it but suspect the Django ORM is capable.
What's the proper and most efficient way to do this?
Models:
class User(Model):
id = IntegerField()
username = CharField()
email = CharField()
class Meta:
db_table = "auth_user"
class AppUser(Model):
user = OneToOneField(User, primary_key=True)
group = ForeignKey('Group', null=True, on_delete=SET_NULL)
zip = CharField()
class Meta:
db_table = "app_users"
class Group(Model):
creator = ForeignKey(AppUser, related_name='+')
created = DateTimeField()
name = CharField()
class Meta:
db_table = "groups"
The trick is to always start from the model you actually want to fetch. In this case, you want to fetch emails, which is a field on the User model. So, start with that model, and use the double-underscore syntax to follow the relationships to Group:
users = User.objects.filter(appuser__group_id=group_id)
In this case, you actually only need a single JOIN, because group_id is a field on AppUser itself (it's the underlying db field for the group ForeignKey). If you had the group name, you would need two joins:
users = User.objects.filter(appuser__group__name=group_name)