I am using Flask/Django to create my database model so I understand Python code but SQL is fine as well.
I was wondering how I can create a database filled with options from a list in that database and I was hoping someone could point me in the right direction or give me an example.
This is going to be a REST API and I want the data to be returned in JSON as well as use curl to test it.
E.g. What I want the tables to look like
Food:
Apples
Oranges
Pears
Sugar
Recipe:
Description: Baked Pears (can be changed by user)
Needs: Pears, Sugar
(User can only choose from the Food list)
User sends request to the API to create a new recipe. It calls the list of food options and the Javascript client lists those options to choose from. Then the user posts his recipe to the database. I am lost how to have the database relate the Food items to the created Recipes.
Sounds like you would need to use Django's many to many relationship. In your example, the Recipe would contain a many to many relationship to the Food.
from django.db import models
class Food(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Recipe(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
ingredients = models.ManyToManyField(Food)
def __str__(self):
return self.title
Django 1.7 Docs: many_to_many
Related
I am trying to draw the table diagram of a product listing web application.
Application logic:
Admin user will create:
Categories (must be dynamically created by admin user),
Category's attributes (must be dynamically created by admin user),
Selection of Category attribute's options (must be dynamically created by admin user)
User will post a product under a specific category and must choose category attribute's option for each category attributes to successfully save the product.
Example: Admin creates category "food"
"food" has its attribute "meal_type" and "sugar".
"meal_type" has its options "breakfast", "lunch" and "dinner".
"sugar" has its options "with-sugar" and "non-sugar".
and now user can post his product "pizza" under category "food".
When user chosen "food" category, he must see its attributes "meal_type" and "suger"
and then must set those option values.
For example, "pizza"'s category is "food" and "meal_type"="breakfast", "sugar"="with-sugar".
And I want to call these option values together with product details when selecting these items.
I have made this (removed non-related fields)
but I am not sure this will work and be efficient at same time.
What is the most efficient relational schema (or ERD) for case like this?
I could help, but I don't really understand what exactly a user is supposed to do? Is he supposed to order products on the website? If so, maybe the naming of the tables should be different, eg "order_product" instead of "product"?
and as for the performance, at this stage and with this structure there should be no problems.
I want to know that how can we get list of required field data from django models. In my case i want to get all usernames from users models.
receivers = User.objects.all()
this return all users objects. I want to get usernames directly. Something like below:
receivers = User.objects.all(username)
output:
["ahmed","dummy","hamza","sentence"]
in sql query looks like below:
SELECT username from USER
receivers=User.objects.values_list('username', flat=True)
Try this code, you can read more about this in django offical documents
receivers = User.objects.all().values_list('username')
It will return list of all usernames.
Image I have following models:
class Product(models.Model):
name = models.CharField(max_length=20)
class Receipt(models.Model):
product = models.ForeignKey(Product)
user = models.ForeignKey(User)
I have an input list of product ids and a user. I want to query for each product, whether it's been purchased by this user. Notice I need a queryset with all exist products based on given input because there are other fields I need for each product even not purchased by this user, so I cannot use Product.objects.filter(receipt__user=user).
So can I create a temp Boolean field to present this property in one single query? I am using Django 1.8 and postgresql 9.3
Update requirements:To separate products into two groups. One is bought by this specific user, the other one is not. I don't think any given filter can implement this. This should be implement by creating a new temp field either by annotate or F expression.
I think, you need .annotate() expression as
from django.db.models.expressions import Case, When, Value
product_queryset = Product.objects.annotate(
is_purchased=Case(
When(receipt__user=current_user, then=Value('True')),
default=Value('False')
))
How to access the annotated field?
product_queryset.first().is_purchased
Thx for #JPG's answer.
I just realize except conditional expressions, there's another easy way to do it.
Just using prefetch_related will implement everything in two queries. Although it's double than conditional expressions, but it's still a considerable time complexity solution.
products = Product.objects.filter(id__in=[1,2,3,4,5]).prefetch_related ('receipt_set').all()
Then we can detect user for this product in Python by
for p in products:
print user in [receipt.user_id for receipt in p.purchase_set.all()]
I'm a Django beginner. I have two models that I would like to display as one table in the Django admin interface. Below are the simplified versions of the models:
class Final_Application_Personal_Detail(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=20)
id_no = models.CharField(max_length=14)
class Final_Application_Beneficiary_Detail(models.Model):
user = models.ForeignKey(User)
beneficiary_name = models.CharField(max_length=20)
beneficiary_id_no = models.CharField(max_length=14)
I suppose because these two models conceptually form part of one form (a Final_Application form), I could have maybe used Django's formwizard - however, because in reality both personal details and beneficiary details are quite a lot to fill in, I thought I'd want to give the user a chance to fill them in separately (in django formwizard, as far as I know, if the user doesn't fill out all the data at once, then all previous data is also lost because the form can't be saved with unvalidated fields).
I want to join the two models in Django admin so that the administrative user can see all a user's information (personal details and beneficiary's details) on one page. So, I'd like to do an inner join on the above-mentioned tables on the field 'user'. The SQL would look like this:
SELECT *
FROM Final_Application_Personal_Detail
JOIN Final_Application_Beneficiary_Detail
ON Final_Application_Personal_Detail.user = Final_Application_Beneficiary_Detail.user
With regards to Django's ORM, I've looked into the keyword argument related_to in order to join the tables. I don't think that will work, however...it seems as if 'select_related' is just another way to stipulate a foreign key. I now want to use raw SQL in order to join the tables. I've tried using the cursor function to implement raw SQL, but I don't quite know how to implement it so that the output shows in Django's admin interface. Also, I'm a little bit afraid of using raw SQL, because as far as I understand, raw SQL can introduce security risks (I've read that Django's ORM prevents SQL injections).
Thank you for your help.
You can't do this with django admin. However, you can use inlines to edit both models in the User admin.
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
class Final_Application_Personal_DetailInline(admin.StackedInline):
model = Final_Final_Applicationl_Detail
class Final_Application_Beneficiary_DetailInline(admin.StackedInline):
model = Final_Final_Application_Beneficiary_Detail
admin.site.unregister(User)
#admin.register(User)
class CustomUserAdmin(UserAdmin):
inlines = [
Final_Application_Personal_DetailInline,
Final_Application_Beneficiary_DetailInline,
]
I have learned about the database concepts in django tutorial book. I have some doubts about to fetch data from the table in sql database server. In django book they explained something like this to filter data as like as below
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
Here Entry is the class name which is defined in models.py file like below
models.py
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()
def __str__(self): # __unicode__ on Python 2
return self.headline
In the above method there is nothing mention about the table to modified. Then which table it is going to be modified in the below query.
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
If i asked anything wrong please forgive me. Can anyone clear my doubts.
From the docs on table names:
To save you time, Django automatically derives the name of the database table from the name of your model class and the app that contains it. A model’s database table name is constructed by joining the model’s “app label” – the name you used in manage.py startapp – to the model’s class name, with an underscore between them.
For example, if you have an app bookstore (as created by manage.py startapp bookstore), a model defined as class Book will have a database table named bookstore_book.
To override the database table name, use the db_table parameter in class Meta.
You don't need to know the table name, if you use the API like you have listed:
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
Django will know what table to update, because of the model you have referenced.
The name of table is determined by model parameter "table_name". If you don't specified it, django automatically derives the name of the database table from the name of your model class and the app that contains it: https://docs.djangoproject.com/en/dev/ref/models/options/#db-table
If your question is about performing SQL queries in django, this will be helpful: https://docs.djangoproject.com/en/dev/topics/db/sql/