I'm new to django. What I'm trying to achieve is when the ProductType combobox is changed, the fields changes to its specific fields then the users inputs using those field and entered to the database. My problem is how to create a flexible model that would accept extra fields
from django.db import models
class Product(models.Model):
"""SKU"""
stock = models.IntegerField(default=None)
class ProductType(models.Model):
product_field = models.ForeignKey(ProductFields, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
class ProductFields(models.Model):
"""Fields of ProductType"""
Here's an DB example I'm trying to achieve See Image
SQL database is not suitable for that purpose.
Look for non-SQL databases for ex. Firebase
Related
In my models.py my model store contains name, brand_name fields
Now,I want to create new field called brand_type in store model dynamically from Django admin,how can I do this?
Can we change schema of model using SchemaEditor? How?
you can't create model's fields via admin panel
you must create fields in models.py
admin panel is only a convinient way to manipulate your database, but not modifiyng its tables
It requires migration while the server is running. Create brand_type field under your model and set blank=True
In your models.py
class Store(models.Model):
name = ...
brand_name = ...
brand_type = models.CharField(max_length = 40, blank= True, null =true)
In your console
./manage.py makemigrations
./manage.py migrate
Extra Stuff:
If you are interested in Text Choices
or
If you wanna make it more dynamic based on your use case,
create a model called BrandType and link it in Store using
brand_type = models.ForeignKey(BrandType,on_delete=models.PROTECT)
models.py
class BrandType(models.Model):
name = ...
some_other fields=
#... Store model follows
admin.py
# other stuff
from .models import BrandType
admin.site.register(BrandType)
Take away: It is not advisable to modify your models.py file using admin directly it will cause integrity issues and there are better ways to achieve your desired functionality.
I mostly work with Node.js & MongoDB and I am pretty new to SQL dbs especially postgreSQL I am writing an application that makes use of django-rest-framework & postgreSQL as a DB.
This is how my data structure as .json should look like.
{
id: "19eea956-34e5-11eb-adc1-0242ac120002"
picture: [{
url: "",
mimeType: ""
},
{
url: "",
mimeType: ""
}]
}
For the above data I am currently writing models.py which looks like as follows.
from django.db import models
from django.contrib.postgres.fields import ArrayField
class Picture(models.Model):
url = models.CharField()
mimeType = models.CharField()
class A(models.Model):
id = models.CharField(max_length=120, primary_key=True)
picture = ArrayField(Picture)
def __str__(self):
return self.id
What I am trying to do in my models.py is to have picture as an Array of Objects or in python terminology List of Dictionaries.
I read about ArrayField in postgreSQL but unable to find any example about how to define Array of Objects in models.py, any help here would be appreciated.
Thanks :)
In relational databases relations are defined by Foreign Keys and different tables. Tables are represented by Django's models, but the programmer should work from the model side of things and think of the database as the object persistence (storage of the state of an object).
Fields should as a rule be single values, not containers. Explaining why distracts too much from the problem at hand, but here's the in-depth info.
In this case, you have two entities, let's call A "Gallery" for clarity. A Gallery object has 1 or more pictures. A picture can be associated with 1 gallery (business rule). There are 2 properties associated with the image: url and mime type.
Now there's several ways to deal with images and that depends whether the image is uploaded or really a URL to a remote image.
I'm going to pick the second option for brevity:
import uuid
from django.db import models
class Gallery(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
name = models.CharField(max_length=40)
class Picture(models.Model):
url = models.URLField()
mime_type = models.CharField(max_length=25)
gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name='pictures')
This creates the correct relation for the image in a way that is preferred by both Django and relational databases.
Now we need to serialize the picture to just the url and mime type field:
from rest_framework import serializers
from .models import Picture, Gallery
class PictureSerializer(serializers.ModelSerializer):
class Meta:
model = Picture
fields = ['mime_type', 'url']
Continuing, we need to nest the pictures into the gallery:
class GallerySerializer(serializers.ModelSerializer):
pictures = PictureSerializer(many=True)
class Meta:
model = Gallery
fields = ['id', 'pictures']
And this should do the trick.
The reason people downvoted is most likely because this is a Q&A site and your scope as demonstrated by my answer is far too big for that. I've given you some handles to work with, but it's best you hit the Django tutorial to get a basic sense of models, followed by the DRF counterpart.
I am making a Manual admin as part of a big project. Each manual has a brand, a model and has at least one PDF.
from django.db import models
class Manual(models.Model):
brand = models.CharField(max_length=255)
model = models.CharField(max_length=255)
manual = models.ImageField(upload_to='pdf')
Two questions:
How can I model a PDFField, or a generic field, rather than an Image field?
Is it possible for the manual field to have more than one file without having to make another table?
Thanks!
If you need to have more than one pdf per manual, use a one-to-many relationship as a ForeignKey in another table. There's nothing wrong with having multiple models.
class Manual(models.Model):
brand = models.CharField(max_length=255)
model = models.CharField(max_length=255)
class ManualPDF(models.Model):
manual = models.ForeignKey(Manual)
pdf = models.FileField(upload_to='pdf')
In your view code (or form or model code) you can then get all the PDFs for a manual using _set which will return a QuerySet of the ManualPDF model objects:
some_manual = Manual.objects.get(id=1)
some_manual_pdfs = some_manual.manualpdf_set.all()
There more info in the official Django docs:
https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_one/
My web application allow users to load/create tables in the Postgres database. I know Django ORM needs a model definition in models.py for each table in the database to access it. How can I access the user's uploaded tables in the app without creating a new model definition on the fly each time a new table is uploaded? I was thinking about creating a generic model definition that decompose the table into its components like this:
models.py
class Table(models.Model):
filename = models.CharField(max_length=255)
class Attribute(models.Model):
table = models.ForeignKey(Table)
name = models.CharField(max_length=255)
type = models.IntegerField()
width = models.IntegerField()
precision = models.IntegerField()
class Row(models.Model):
table = models.ForeignKey(Table)
class AttributeValue(models.Model):
row = models.ForeignKey(Row)
attribute = models.ForeignKey(Attribute)
value = models.CharField(max_length=255, blank=True, null=True)
The problems with such a generic model is that every tables are mixed in 4 table (not useful in admin interface) and its really slow to create when you have a lot of rows. Do you have suggestion with this case?
Edit: Could it be viable to use a separate database to store those tables and use a router and manage.py inspectdb to update its models.py each time a user add or delete a table? (like in this post) I wonder what would happen if two users add a table in the same time?
I think you should look into dynamic models like here:
https://code.djangoproject.com/wiki/DynamicModels
or here:
http://dynamic-models.readthedocs.org/en/latest/
Good luck because its not an easy way my friend :)
You'll probably need to use raw SQL queries for doing this.
If the schema of the tables you are expecting are predefined you can use a database router to link some model to a specific table name for each user.
I have a n existing MySQL database. I want to create a new django application with that database.
I read that I need to run "syncdb" each and every time when add a new model in django. That time adding a new table in database in <database_name>.<table_name> format. And fetching data from that table.
What is the correct method to fetch data from an existing database in django ?
This is my model:
from django.db import models
class Users(models.Model):
employee_id = models.CharField(max_length=30)
def __unicode__(self):
return self.employee_id
Use the Django model meta options to set db_table and db_column on your Models and Fields respectively. See these links for more info on how to use them:
https://docs.djangoproject.com/en/dev/ref/models/options/#db-table
https://docs.djangoproject.com/en/dev/ref/models/fields/#db-column