Foreign key choosable when create the model instance - python

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.

Related

Adding Foreign Key to model - Django

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.

Add Tables As A Field In Django Python

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)

Add relationship to three tables with data and strange column names

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.

How to consider a related field in unique key in Django?

I have a following django models:
class Entity(models.Model):
name = models.CharField(max_length=255)
class EntityProp(models.Model):
entity = models.ForeignKey('Entity')
key = models.CharField(max_length=255)
value = models.CharField(max_length=255, blank=True, default='')
I want to make a unique key for Entity that includes name and related EntityProp. For example, I want two entities with the same name and different set of related EntityProp instances to be different. But I want to keep the same Entity if they have identical names and EntityProp instances. Is there an elegant way to do it in Django?
As a reserve way I can create an additional field in Entity called props_hash that contains a hash of the identifiers of all related instances, but it wouldn't be easy to support such structure, I think. So I believe there's a better way.
Here you go
class Entity(models.Model):
name = models.CharField(max_length=255)
class EntityProp(models.Model):
entity = models.ForeignKey('Entity')
key = models.CharField(max_length=255)
value = models.CharField(max_length=255, blank=True, default='')
class Meta:
unique_together = ('key', 'entity')
Source: https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together

dynamic table name and dynamic field for django 1.8

My requirement is: create category and product table according to the store selected.
class Category(models.Model):
parent = models.ForeignKey("Category", blank=True, null=True,
related_name="children", verbose_name=_("Parent Category"))
name = models.CharField(verbose_name=_("Name"), max_length=255)
path = models.CharField(verbose_name=_("Path"), max_length=200)
description = models.TextField(verbose_name=_("Description"))
class CategoryStore(model.Model):
default = models.ForeignKey("Category", related_name="store_category",
verbose_name=_("Default Value"))
parent = models.ForeignKey("CategoryStore", blank=True, null=True,
related_name="children", verbose_name=_("Parent Category"))
name = models.CharField(verbose_name=_("Name"), max_length=255)
description = models.TextField(verbose_name=_("Description"))
store = models.ForeignKey("Store", related_name="store_category",
verbose_name=_("Store"))
CategoryStore model will have table names as category_store_1, category_store_2, etc. Would like to create the tables on the fly after a store is created. If, we add another field to the model, should have option to add to all the tables the new field.
class Product(models.Model):
name = models.CharField(verbose_name=_("Name"), max_length=255)
description = models.TextField(verbose_name=_("Description"))
class ProductStore(model.Model):
default = models.ForeignKey("Product", related_name="store_product",
verbose_name=_("Default Value"))
name = models.CharField(verbose_name=_("Name"), max_length=255)
description = models.TextField(verbose_name=_("Description"))
store = models.ForeignKey("Store", related_name="store_product",
verbose_name=_("Store"))
This also has same requirement as the category. One addition is that, option to create new field to both the model, new field on the fly from admin form. It will be attributes for the product. Instead of another table to store attribute values, want to add a new field to the Product and ProductStore model on the fly.
Not sure if I fully understand your problem, but it seems to me that you should reconsider your database structure. I'm not very experienced but adding tables to db on a regular basis on the fly is not good.
CategoryStore model will have table names as category_store_1, category_store_2, etc.
Keeping in mind that in django 1 model <=> 1 db table, try this approach: one table called CategoryStore which holds data from all your stores and another table called CategoryStoreType with the following structures:
CategoryStore has all the fields you need plus a type field which is a foreign key to CategoryStoreType. CategoryStoreType contains a short description of each store type, e.g. a tuple ('id', 'type name'). This way when you need a new field for one store type you simply add another field to CategoryStore, which holds data of all your store types. (Again, as for tables, adding fields on the fly is not that good, imho.)

Categories

Resources