Django modeling problem, need a subset of foreign key field - python

I intend to create an app for categories which will have separate category sets (vocabularies) for pages, gallery, product types etc. So there will need to be two models, vocabulary and category.
The categories/models.py code might be something like this:
class Vocabulary(models.Model):
title = models.CharField()
class Category(models.Model):
title = models.CharField()
vocabulary = models.ForeignKey(Vocabulary)
From my pages, blogs, gallery, etc apps how I will need a ForeignKey field to categories:
class Page(models.Model):
title = models.CharField()
content = models.TextField()
category = models.ForeignKey('categories.Category')
This will of course list all available categories in the admin app. If I have a product I want only the product categories to be avaialble. How can I filter the available categories to a specific vocabulary?
I'm learning Django and not really sure where to begin. Maybe I have the whole model wrong? If there are any apps which already do it please let me know.

Filtering of selection like this is done in the form using a queryset, or in the admin interface with limit_choices_to.

Related

Multiple Django Forms on Single Page

I'm trying to create a form to input scores for a round of golf. A standard round of golf is 18 holes, so the form should create 18 instances of 'Score' once submitted. How would I go about creating a form that contains a single dropdown for 'player' and 18 text fields for strokes on each hole? Below are the models being used:
class Score(models.Model):
hole = models.ForeignKey(Hole, on_delete=models.CASCADE)
player = models.ForeignKey(Player, on_delete=models.CASCADE)
strokes = models.IntegerField(default=0)
class Player(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
class Hole(models.Model):
number = models.IntegerField()
Have a look at Django Inline Formsets. This allows you to include multiple forms per view and the inline formset allows you to work with objects related by a foreign key.
It is relatively easier when you know the exact amount of forms you need to include in your template. However, if you want to dynamically include forms in your template then you will need to look into adding some javascript to provide this functionality.

How to save the data that has same model but with different data in Django

I'm working on a mini project which uses Django 1.8. The aim is to build a small billing app. So, I've created two models, Bill and Product, as follows.
#bill/models.py
class Bill(models.Model):
date_of_issue = models.DateField()
name = models.CharField(max_length=50, default="N/A", null=True)
address = models.CharField(max_length=150, default="N/A", null=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
return "{} {}".format(self.input_name, self.date_of_issue)
class Product(models.Model):
bill = models.ForeignKey(Bill, on_delete=models.CASCADE)
description = models.CharField(max_length=100, default="N/A")
quantity = models.IntegerField(default=0)
total = models.IntegerField(default=0)
By seeing the model, you can tell that my approach is to create Bill and Product tables and connect the Product to Bill via ForeignKey. Now, the thing is that a single bill will contain at least one product. If there are more than one product, how should I write my views in views.py. I'm a beginner in the Django development. If a Bill contains a single Product then I can write its view. But how can I store multiple Product which have different data and storing it in database.
For Example
The user will enter the name and address of the customer. Then the user will enter the details of products. Now I want to generate the Product modelform more than once (depends upon the number of products added by user). How can I accomplish this ?
Assuming
1) multiple products can be bought at once (and thus be part of one bill) and
2) one product can be bought multiple at any time (and thus be part of many bills)
a simple foreign key is the wrong modelling attempt. Instead of a m:1 relation you need a m:n relation - and thus a ManyToManyField. With a ManyToManyField you can add multiple products to one bill or have mutiple products added to multiple bills. In django-admin it's useful (and I recommend it) to put ManyToManyFields as filter_horizontal which eases the use of this field.
Plus, django will automatically resolve your m:n relation with an additional third database table, so you don't need to take care of this.

How to model this kind of a relationship in django?

I want to have two models:
class Receipt(models.Model):
# Bunch of products
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField()
I don't want the product to know about receipt but just the receipt to know about the products. How do I build this relationship?
PS: One product can be in multiple receipts.
If it is just like you say a manyTomanyField is enough.
But if you need to store also the quantity of each ingredient on each receipe then do you need a many2many with attributes relation
One2Many relationship doesn't come out the box with Django. However, I think this answer is what you're after : Django one-to-many field without reversing dependency

Django OneToOneField, ManyToManyField, Foreign Key

I've read many posts on what OneToOneField, ManyToManyField, and Foreign Key are but they aren't very clear. I am very new to Django and python programming, currently trying to develop models. Can someone explain to me in simple language, preferably with example, what they each are?
Imagine a database, which stores your book collection:
from django.db import models
class Place(models.Model):
address = models.CharField(max_length=50)
country = models.CharField(max_length=50)
class Publisher(models.Model):
name = models.CharField(max_length=30)
place = models.OneToOneField(Place, primary_key=True)
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
class Book(models.Model):
title = models.CharField(max_length=100)
publisher = models.ForeignKey(Publisher)
authors = models.ManyToManyField(Author)
One-to-many/Foreign Key
Every Book has one Publisher, but a Publisher might have published multiple books. Therefore they are in a one-to-many (book-to-publisher) relationship.
One-to-one
Every Publisher is located in one Place, and every Place can only hold one Publisher. Therefore they are in a one-to-one relationship. You could just have well have put the Place information (address and country) with the Publisher model in one table, but sometimes it is preferred to have seperate models. For example, if you do not know the Place for every Publisher, you don't need to take up a lot of space with empty rows.
Many-to-many
Every Book also has one or more Authors. However, an Author might have written multiple Books, so they are in a many-to-many relationship.
If you still need some guidance, I suggest taking a look at the model chapter of the Django Book.

Querying for followers in news-feed-based data model in Django

I have this following (simplified) model in Django which is very similar to the Pinterest data model:
class UserProfile(models.Model):
user = models.OneToOneField(User)
class Collection(models.Model):
owner = models.ForeignKey(User,related_name='collection_owner')
followers = models.ManyToManyField(User, related_name='collection_followers', null=True, blank=True, default = None)
class Item(models.Model):
collections = models.ManyToManyField(Collection,blank=True,null=True)
I have a User model, a UserProfile model that maps 1-1 with a user, a Collection model which has an owner and followers and items that can be part of multiple collections. I'm struggling with determining how to execute the following queries in Django:
Get all the followers of a given user. The definition of a follower is one that follows at least one collection that is owned by that particular user.
Get all the distinct items of the collection a user follows.
I'm not sure if I can do these in a single query or do I have to break it up in several queries? What would be the best approach and are there any trade offs?
Thanks for any help.
The first would be something like this I think:
User.objects.filter(collection_owner__owner='the user')
The latter should be something like this:
Item.objects.filter(collections__followers='the user').distinct()
You should be aware however that these type of queries do not scale to large amounts of data. Doing that will require quite a bit of hacking...

Categories