Add Tables As A Field In Django Python - 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)

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.

Django Form - Filter a list based on Foreign Key Value

So basically I have the following in my models.py
class Company (models.Model):
title = models.CharField(max_length=100)
short = models.CharField(max_length=50,default='NA')
class AccountingGroups(models.Model):
title = models.CharField(max_length=50, unique=True)
description= models.CharField(max_length=150,blank=True)
section = models.ForeignKey(Section, on_delete=models.PROTECT)
class Transaction (models.Model):
description = models.CharField(max_length=100)
date_created= models.DateField(auto_now_add=True)
posting_date = models.DateField()
user=models.ForeignKey(User, on_delete=models.PROTECT)
company = models.ForeignKey(Company, on_delete=models.PROTECT)
account_group = models.ForeignKey(AccountingGroups, on_delete=models.PROTECT)
income_amt = models.DecimalField(max_digits=6, decimal_places=2,default=0)
expenditure_amt = models.DecimalField(max_digits=6, decimal_places=2,default=0)
Now I am displaying the transaction Form on the browser so to log in all the income and expenditure of a particular company. The below is the forms.py file.
class TransactionForm(ModelForm):
#posting_date = DateField(input_formats=['%d/%m/%Y'])
posting_date = DateField(widget=DatePickerInput(format='%d/%m/%Y').start_of('event active days'),
input_formats=('%d/%m/%Y',),
required=False)
class Meta:
model = Transaction
fields = ['description','posting_date','account_group','income_amt','expenditure_amt']
Now the structure of the website is that each each company that i have in my database has a distinct url. When i go to each url i can view/edit or create a new/existing transaction for that particular company. Now what I'm asking if whether I can restrict the form so that it will show only the Accounting Groups for that particular company only rather than displaying all the accounting groups irrespective on which company I m trying to create the transaction on.
If you are looking to display a Company's AccountingGroups (and not transactions), you need a foreign key to filter off of. You currently don't have any in your AccountingGroups table, unless your Section FK links up to Company. Then you just query off that foreign key relationship.
AccountingGroups.objects.filter(section__company_id=pk)
No matter how you do it, you will need to pass in the company_id via your request.

How can i filter a manytomany field based on a foreign key?(I the django Admin panel itself)

I have a many-to-many relation on field tag and a foreign key field appName, I want to select only the tags that are related to the specific appNames.
Now, when the dropdown for selection is opened it displays all the many-to-many fields irrespective of its related apps.
class AppName(models.Model):
appId = models.AutoField(primary_key=True)
appName = models.CharField(max_length=200)
appVersion = models.CharField(max_length=100,blank=True)
appVersionName = models.CharField(max_length=100,blank=True)
appPackageName = models.CharField(max_length=300)
class Tag(models.Model):
tagId = models.AutoField(primary_key=True)
tag = models.CharField(max_length=300)
tagDes = models.TextField()
tagAddedDate = models.DateTimeField(default=timezone.now)
appName = models.ForeignKey(AppName,on_delete=models.CASCADE, null=True, blank=True)
class Company(models.Model):
CId = models.AutoField(primary_key=True)
appName = models.ForeignKey(AppName,on_delete=models.CASCADE, null=True, blank=True)
tag = models.ManyToManyField(Tag,blank=True)
The expected output is a list of tags with respect to the appName selected.
The question is not entirely clear for me, but it seems that you want to have 'chained' dropdown lists. As far as i know it is not doeable without some requests.
I followed tutorial from:
https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html
and it worked perfectly in my case. So basically you need some ajax requests.

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.

Django Admin: Add foreign keys at same time as model

I am a novice in Django and I'm learning the ropes of the admin interface. I have a model with several foreign keys. These foreign keys then reference other foreign keys. On the admin website after I register the Property model and then try to add it I am given a dropdown box for each foreign key model. However this dropdown box only lists existing foreign keys. (http://i.stack.imgur.com/e5LCu.png)
What would be great is if instead of a dropdown box there were extra fields so I could add the foreign key models as I add the property model. That way I wouldn't have to manually add foreign keys and then go back and add some more, and then go back and finally add the property data.
How can I do this? This feels like a simple enough question but after intense Googling I still can't find the answer, so I apologize in advance.
Example of two of my models:
class Address(models.Model):
state = models.ForeignKey('State')
address1 = models.CharField(max_length=200)
address2 = models.CharField(max_length=200)
city = models.CharField(max_length=200)
postal_code = models.CharField(max_length=200)
class Property(models.Model):
address = models.ForeignKey('Address', blank=True, null=True)
borrower = models.ForeignKey('Person', blank=True, null=True)
company = models.ForeignKey('Company', blank=True, null=True)
contract = models.ForeignKey('Contract', blank=True, null=True)
loan_balance = models.IntegerField()
name = models.CharField(max_length=200)
primary_email = models.CharField(max_length=200)
primary_phone = models.CharField(max_length=200)
property_no = models.IntegerField()
Example of my admin.py:
# Register your models here.
class PropertyAdmin(admin.StackedInline):
model = Property
class PersonAdmin(admin.StackedInline):
model = Person
class CompanyAdmin(admin.StackedInline):
model = Company
class ContractAdmin(admin.StackedInline):
model = Contract
class CompletePropertyAdmin(admin.ModelAdmin):
inlines = [PropertyAdmin, PersonAdmin, CompanyAdmin, ContractAdmin]
admin.site.register(Property)
One solution to the problem can be, to create a custom form with fields from both the models and at the time of saving the values, first create the instance of Address model and then with that instance save your final Property model.

Categories

Resources