Create a MultipleChoiceField using rows from another model, - python

I am creating an online job application for a company with multiple locations. I would like to allow the applicant to be able to select checkboxes that represent every store they would like to apply to (could be multiple). I am hesitant to hard code these for scalability purposes, so I had hoped to create 2 models (I have more than that, but for this example these are the only 2 that are relevant):
Applicant
class Applicant(models.Model):
name = models.CharField(max_length=200)
city = models.CharField(max_length=200)
state = models.CharField(max_length=200)
zip = models.CharField(max_length=200)
social_security_number = models.CharField(max_length=200)
phone = models.CharField(max_length=200)
alt_phone = models.CharField(max_length=200, blank=True)
us_citizen = models.BooleanField()
committed_felony = models.BooleanField()
is_16 = models.BooleanField()
has_drivers_license = models.BooleanField()
is_disabled = models.BooleanField()
prev_employed = models.BooleanField()
felony_explanation = models.TextField(blank=True)
disabled_explanation = models.TextField(blank=True)
prev_employment_manager = models.CharField(max_length=200, blank=True)
prev_employment_year = models.CharField(max_length=4, blank=True)
skills = models.TextField()
was_completed = models.BooleanField(default=False)
def __unicode__(self):
return self.name
Store
class Store(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=200)
city = models.CharField(max_length=20)
state = models.CharField(max_length=20)
def __unicode__(self):
return self.description
I would (I think) like to add a MultipleChoiceField in the applicant model, that creates choices from all of the instances of Store (one for each row). So far, I have tried this in the applicant class:
def get_stores():
self.stores = Store.objects.all()
but was unable to (as far as I can tell) grab the instances of Store like I had hoped. Here are a few questions I have:
Is it even possible to reference another model like that?
Is referencing the Store model from the Applicant model the right beginning for creating several checkboxes to let an applicant select all of the stores they are applying to (and allow the list to change dynamically)?
is a MultipleSelectField the best way to do this once I have pulled all of the Store instances?

This seems like the canonical use case for ManyToManyField.
class Store(models.Model):
...
class Applicant(models.Model):
name = models.CharField(max_length=200)
...
was_completed = models.BooleanField(default=False)
stores = ManyToManyField(Store, related_name='applicants')
When you display this form in a field, it should automatically use a MultipleSelectField
REF: https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

Related

What is the best way to handle different but similar models hierarchy in Django?

What is the deal: I'm crating a site where different types of objects will be evaluated, like restaurants, beautysalons, car services (and much more).
At the beginning I start with one app with with Polymorfic Model:
models.py:
from django.db import models
from users.models import ProfileUser
from django.utils import timezone
from polymorphic.models import PolymorphicModel
class Object(PolymorphicModel):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2)
created_date = models.DateTimeField(default=timezone.now)
approved_object = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
def __str__(self):
return f"{self.title}"
class Restaurant(Object):
seats = models.IntegerField()
bulgarian_kitchen = models.BooleanField(default=False)
italian_kitchen = models.BooleanField(default=False)
french_kitchen = models.BooleanField(default=False)
sea_food = models.BooleanField(default=False)
is_cash = models.BooleanField(default=False)
is_bank_card = models.BooleanField(default=False)
is_wi_fi = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='restaurants')
category_bg_name = models.CharField(max_length=100, default='Ресторанти')
bg_name = models.CharField(max_length=100, default='Ресторант')
is_garden = models.BooleanField(default=False)
is_playground = models.BooleanField(default=False)
class SportFitness(Object):
is_fitness_trainer = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='sportfitness')
category_bg_name = models.CharField(max_length=100, default='Спорт и фитнес')
bg_name = models.CharField(max_length=100, default='Спорт и фитнес')
class CarService(Object):
is_parts_clients = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='carservice')
category_bg_name = models.CharField(max_length=100, default='Автосервизи')
bg_name = models.CharField(max_length=100, default='Автосервиз')
class Comment(models.Model):
object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
content = models.TextField()
rating = models.TextField()
approved_object = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.content}"
class Images(models.Model):
object = models.ForeignKey(Object, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='attachments',
verbose_name='Image')
class ObjectCoordinates(models.Model):
object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='coordinates')
latitude = models.CharField(max_length=60)
longitude = models.CharField(max_length=60)
Don't mention that name Object is wrong, I already know that :)
So all logic about different objects was in one App and this start to cause some problems, like:
views.py:
def show_object(request, category, pk, page_num):
categories = {'restaurants' : 'Restaurant', 'sportfitness' : 'SportFitness', 'carservice' : 'CarService'} # probably this is not good way to do it
obj = apps.get_model('objects', categories[category]).objects.get(id=pk)
def show_all_objects(request, category, page_num, city=None):
params_map = {
'restaurants': Restaurant,
'sportfitness': SportFitness,
'carservice': CarService,
}
objects = Object.objects.instance_of(params_map.get(category))
and other problems in templates (a lot of if-else blocks) etc.
So I decide to change whole structure and put every model in different app, so now I have app:restaurants, app:sportfitness, app:carservices, etc. But it begin to cause some problems, again, like this model:
class ObjectCoordinates(models.Model):
object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='coordinates')
latitude = models.CharField(max_length=60)
longitude = models.CharField(max_length=60)
All of objects (restaurants, car services) has coordinates of map, so I'm not sure how to handle it, with Model ObjectCoordinates . If I create ObjectCoordinates for each of them, respectively a table in BD (then I will have some tables with different names but same structure, which is not very good, because except ObjectCoordinates, models share and other common models like Images and others, so at the end I will have a lot of tables with different names and same structure). Probably I should add one more column for object category, if I got two rows with same id of objects?
Probably change ObjectCoordinates and other common models to ManyToMany relation will prevent identical tables, but I'm not quite sure about that. Other problem is that there is a lot of repeated code (in views, templates). Also, now, I don't know how to get all objects (restaurants, car services) when they do not have common point, like Object model in first scenario with Polymorphic Model. Or I should keep different apps but to create common Model for all objects, and all of them to to inherit it.
Questions:
What structure is better, first one or second one?
What is the best wayt to implement such site (model structure)?
Should I create common point (model) for all models who they will inherit?
Here is my third attempt (notice that Object is renamed to Venue):
from django.db import models
from users.models import ProfileUser
from django.utils import timezone
from polymorphic.models import PolymorphicModel
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return f"{self.name}"
class Category(models.Model):
name = models.CharField(max_length=20)
bg_name = models.CharField(max_length=20, default=None)
category_bg_name = models.CharField(max_length=100, default=None)
def __str__(self):
return f"{self.name}"
class Venue(models.Model):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2)
created_date = models.DateTimeField(default=timezone.now)
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
venue_category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category')
def __str__(self):
return f"{self.title}"
class VenueFeatures:
seats = models.IntegerField()
bulgarian_kitchen = models.BooleanField(default=False)
italian_kitchen = models.BooleanField(default=False)
french_kitchen = models.BooleanField(default=False)
sea_food = models.BooleanField(default=False)
is_cash = models.BooleanField(default=False)
is_bank_card = models.BooleanField(default=False)
is_wi_fi = models.BooleanField(default=False)
is_garden = models.BooleanField(default=False)
is_playground = models.BooleanField(default=False)
is_fitness_trainer = models.BooleanField(default=False)
is_parts_clients = models.BooleanField(default=False)
is_hair_salon = models.BooleanField(default=False)
is_laser_epilation = models.BooleanField(default=False)
is_pizza = models.BooleanField(default=False)
is_duner = models.BooleanField(default=False)
is_seats = models.BooleanField(default=False)
is_external_cleaning = models.BooleanField(default=False)
is_internal_cleaning = models.BooleanField(default=False)
is_engine_cleaning = models.BooleanField(default=False)
is_working_weekend = models.BooleanField(default=False)
is_kids_suitable = models.BooleanField(default=False)
is_working_weekend = models.BooleanField(default=False)
venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='venue')
class Comment(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
content = models.TextField()
rating = models.TextField()
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.content}"
class Images(models.Model):
venue = models.ForeignKey(Venue, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='attachments',
verbose_name='Image')
class VenueCoordinates(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='coordinates')
latitude = models.CharField(max_length=60)
longitude = models.CharField(max_length=60)
Now I do not now how to use Venue with VenueFeatures
Notice that features are just true/false values (checkboxes in form).
Okay, this is probably the best way to abstract anything as much as I can:
from django.db import models
from users.models import ProfileUser
from django.utils import timezone
from polymorphic.models import PolymorphicModel
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return f"{self.name}"
class Category(models.Model):
name = models.CharField(max_length=20)
bg_name = models.CharField(max_length=20, default=None)
category_bg_name = models.CharField(max_length=100, default=None)
icon = models.CharField(max_length=40, default=None)
def __str__(self):
return f"{self.name}"
class Venue(models.Model):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2)
created_date = models.DateTimeField(default=timezone.now)
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return f"{self.title}"
class Feature(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=100 )
category = models.ForeignKey(Category, on_delete=models.CASCADE)
type = models.CharField(max_length=100)
def __str__(self):
return f"{self.name}"
class VenueFeatures(models.Model): # ManyToMany Venues <-> Features
venue = models.ForeignKey(Venue, on_delete=models.CASCADE)
feature = models.ForeignKey(Feature, on_delete=models.CASCADE)
value = models.CharField(max_length=255)
class Comment(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
content = models.TextField()
rating = models.TextField()
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.content}"
class Images(models.Model):
venue = models.ForeignKey(Venue, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='attachments',
verbose_name='Image')
class VenueCoordinates(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name='coordinates')
latitude = models.CharField(max_length=60)
longitude = models.CharField(max_length=60)
Now Features are bound with Categories
Also Venues are ManyToMany with Features
I have already linked it to business logic and it works fine.
TL;DR Use a JSONField (JSONB automatically I think) in PostgreSQL WITHOUT a GIN index for your VenueFeatures instead of creating an entirely new model. Postgres has come a long way towards NoSQL/unstructured DB and it's really good. Using a JSONField in your Venue model would work really well. At the very bottom, I talk about how I would design your site's db.
Although I hate saying this, but this could be the job of a NoSQL database. Usually every application uses RDBM which is structured, but you are using unstructured attributes. You could try using PostgreSQL's JSONB field but... stuffing everything into one field would be tiresome for the GIN index + caching.
For now, I'll ignore a lot of weird practices such as needing to partition a couple of attributes, max_length for char field is typically 255 length for all databases, making sure the most accessed tables don't have too many attributes so that caching is better (i.e. you don't have to invalidate your cache every time a user updates your table), GeoDjango for your coordinate system with the standard Mercator projection system on Postgres Geography mode, and you could use sets instead of dicts (sets are iterables and use {} but nothing is repeated)...
Stay away from this option: For one, I NEVER recommend MongoDB, but it could be useful for you... so long as your application doesn't grow too large as in a couple million records could break your system.
The other RECOMMENDED option is PostgreSQL's JSONB or Django's JSONField withOUT a GIN index (I strongly recommend you don't index this field since venues could change them sooo often to the point that REINDEXING and caching would burn your server and slow your app). It can be useful to store a venue's "Features" inside of this JSONB field since everything is super unstructured.
Lowering the number of attributes is better. You've got A LOT of them too which could slow down querying. I recommend you use Django-cachalot for caching since they support JSONField which can avoid your issue of having a LOT of attributes.
Other recommendations in general
Instead of using default='', just do blank=True, null=True since you're basically saying the user doesn't have to fill out the email field.
Kind of like how you would have a user profile instead of stuffing ALL of your attributes inside of the main User model, you want to partition your Venue data into different models.
The way I would've designed this:
Since you originally had these three venues, just make the "Categories" table into choices.
from django.contrib.gis.db import models # This also imports standard models
from django.contrib.postgres.fields import JSONField # Remember to turn on GeoDjango with PostgreSQL's PostGIS extension
from django.contrib.postgres.indexes import BrinIndex
class Venue(models.Model):
id = models.BigAutoField(primary_key=True)
title = models.CharField(max_length=255)
rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2)
created_date = models.DateTimeField(default=timezone.now)
approved_venue = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
VENUE_TYPES = [
(1, "restaurant"),
(2, "concert"),
(3, "art night")
]
category = SmallPositiveIntegerField(choices=VENUE_TYPES)
location = models.PointField(srid=4326) # mercator projection from GeoDjango. You don't have to use this; you can stick to your old city and address thing
class Meta:
indexes = (
BrinIndex(fields=['category']), # this is in case you have a LOT of categories later on.
)
class VenueProfile(models.Model):
venue = models.OneToOneField(Venue, on_delete=models.CASCADE, primary_key=True)
misc_features = JSONField() # This field is for stuff like your restaurant features OR your concert features. You can put whatever you want in there. Just make sure you have a list of features that people have when trying to access the JSON so you don't run into exceptions.
created_date = models.DateTimeField(auto_now_add=True)
facebook = models.CharField(max_length=100, blank=True, null=True)
instagram = models.CharField(max_length=100, blank=True, null=True)
city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) # SET_NULL in case you accidentally delete a city. You don't want to also delete the venue.
image = models.ImageField(upload_to='attachments',
verbose_name='Image')
# These attributes are universal for ANY venue so that's why they don't need to be in the JSONField
"""
For the rest of the features, I have no concern EXCEPT for city. Because you're using GeoDjango, you should also use MaxMind's free city database to determine location based on coordinates. That way, you've essentially scraped the need to store the user and such. You could probably save the address field since it could make things easier that a simple coordinate. It's really up to you. You could also use both!
"""
The attributes I've added to the Venue model are THE MOST important things in my opinion that a user would immediately want to know about.
The VenueFeature model is something that isn't updated that much. It's PRIME for using Django-cachalot to take over since it's not modified that often. (50 modifications per second makes invalidation of caches per modification a big hassle).
Comments model is fine.

How can I organize a database with products and users?

I am currently trying to organize a django database model for an online shop-system with users and products.
My code:
class UserData(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=500)
bought_products = models.ForeignKey(MarketProducts, on_delete=models.CASCADE)
class VendorData(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=500)
sold_products = models.ForeignKey(MarketProducts, on_delete=models.CASCADE)
class MarketProducts(models.Model):
category = models.CharField(max_length=100)
vendor = models.ForeignKey(VendorData, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
description = models.CharField(max_length=1000)
price = models.IntegerField()
pub_date = models.DateTimeField('Date published')
image = models.ImageField(upload_to=b'shop/media/images/')
likes = models.IntegerField()
dislikes = models.IntegerField()
How can I organize a good working system so all the products a user bought are saved inside the bought_products column and all the products a vendor sold can be saved inside the sold_products column. Do I have to use a ForeignKey for that or is there something more suitable for this situation? Also, if there is anything unwise about the existing structure of the database model (for example the current image field column only saves the link but not the image itself which is kinda weird...), please feel free to correct me :).
Many thanks in advance :D
In this case I suggest to make bought_products and sold_products instances of ManyToManyField because the same product can be bought by multiple Users and sold by multiple vendors
Firstly I would start by reading the following documentation on django auth customization. Seems like that would help you out a little bit.
https://docs.djangoproject.com/en/2.2/topics/auth/customizing/
Additionally, I think you need to better evaluate your data modelling to make each model more explicit/clearly defined. See example below:
class Products(models.Model):
vendor = models.ForeignKey(VendorData, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
description = models.CharField(max_length=1000)
price = models.IntegerField()
pub_date = models.DateTimeField('Date published')
image = models.ImageField(upload_to=b'shop/media/images/')
likes = models.IntegerField()
dislikes = models.IntegerField()
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=100)
active = models.BooleanField(default=True)
class ProductCategory(models.Model):
product = models.ForeignKey(Products, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
creation_date = models.DateTimeField(auto_add_now=True)
From there I would construct a separate model which would store the customer purchased items. Since you already have a model which stores the vendor to product data, you shouldn't need anything additional to identify how many sales a particular vendor has.

How to process data from one model field to another

I have models of Exercise, Training and Workout.
Training contains some exercises (Exercise)
Workout contains trainings (Training).
Snippet of my models.py:
class Exercise(models.Model):
user = models.ForeignKey(User, related_name='exercises',
on_delete=models.CASCADE)
name = models.CharField(max_length=80)
description = models.TextField(max_length=300)
details = models.ManyToManyField(ExerciseDetail, blank=True)
...
class Training(models.Model):
user = models.ForeignKey(User, related_name='trainings',
on_delete=models.CASCADE)
name = models.CharField(max_length=80)
description = models.CharField(max_length=250)
exercises = models.ManyToManyField(Exercise, related_name='trainings',
blank=True)
...
class Workout(models.Model):
user = models.ForeignKey(User, related_name='workouts',
on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=200)
description = models.TextField(max_length=400, blank=True)
trainings = models.ManyToManyField(Training, related_name='workouts',
blank=True)
...
I would like to have possibility to use something like Workout.objects.get(name='workout').exercises.objects.all() to get a list/set of all exercises included in trainings of chosen Workout.
I would also like to have possibility to use exercises`` field with Django Rest Framework to list all exercises, possibly with link to particularExercise``` model serializer.
Can someone give a hint how can I do that?
You can query this with:
Exercise.objects.filter(
trainings__workouts__name='workout'
)
With the consecutive underscores (__), you thus can look "through" relations.
This will thus return the Exercises that belong to Trainings that belong to Workouts with as name 'Workout'.

Tags for relationship in Django

I'm working on an inventory tracking application. Barebones, just for learning. One issue I'm running into is how products can be related. Categories works fine, but a Logitech G35 Mouse could be nested under Peripherals, but Peripherals will be populated with mice, keyboards, headphones, Waacom pads, etc. To help find what we need faster I wanted to incorporate tags of some sort, but I've noticed there's something called Tags native to Django which keeps hijacking my search.
Here's my Item model:
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=100)
manufacturer = models.ForeignKey('Manufacturer', blank=True, null=True, on_delete=models.SET_NULL)
part_number = models.CharField(max_length=50, blank=True, null=True)
introduction = models.DateField(auto_now=True)
category = models.ForeignKey('Category', default='Uncategorized', on_delete=models.SET_DEFAULT)
quanity = models.IntegerField(default=0)
is_retired = models.BooleanField(default=False)
def __str__(self):
return self.name
def add(self):
pass
def remove(self):
pass
def retire(self): # Rex came up with this, roll credits.
pass
def count(self):
pass
So if I were to add a Logitech G35 Mouse as an item, I'd like the tag(s) to be mouse, mice, wireless and so forth. Where might I find the information needed to implement this?
You can create a model Tag and a many to many relationship with model Item:
class Tag(models.Model)
name = models.CharField(max_length=20)
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=100)
manufacturer = models.ForeignKey('Manufacturer', blank=True, null=True, on_delete=models.SET_NULL)
part_number = models.CharField(max_length=50, blank=True, null=True)
introduction = models.DateField(auto_now=True)
category = models.ForeignKey('Category', default='Uncategorized', on_delete=models.SET_DEFAULT)
quanity = models.IntegerField(default=0)
is_retired = models.BooleanField(default=False)
tags = models.ManyToManyField(Tag)
You probably want a Many-to-Many relationship. You need a table of products, a table of categories, and a table that shows the relationship between those tables. Here is the sample code from the Django docs. A publication can contain many articles, and an article can be in many publications. To translate this to your models, a product(mouse) can be a part of many categories(mice/mouse/wireless), and a category(wireless) can contain many items(mouse, keyboard, speakers)
from django.db import models
class Publication(models.Model):
title = models.CharField(max_length=30)
def __str__(self):
return self.title
class Meta:
ordering = ('title',)
class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
def __str__(self):
return self.headline
class Meta:
ordering = ('headline',)
Link: https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/

django - inlineformset_factory with more than one ForeignKey

I'm trying to do a formset with the following models (boost is the primary):
class boost(models.Model):
creator = models.ForeignKey(userInfo)
game = models.ForeignKey(gameInfo)
name = models.CharField(max_length=200)
desc = models.CharField(max_length=500)
rules = models.CharField(max_length=500)
subscribe = models.IntegerField(default=0)
class userInfo(models.Model):
pic_url= models.URLField(default=0, blank=True)
auth = models.ForeignKey(User, unique=True)
birth = models.DateTimeField(default=0, blank=True)
country= models.IntegerField(default=0, blank=True)
class gameInfo(models.Model):
psn_id = models.CharField(max_length=100)
name = models.CharField(max_length=200)
publisher = models.CharField(max_length=200, default=0)
developer = models.CharField(max_length=200, default=0)
release_date = models.DateTimeField(blank=True, null=True)
I want to display a form to add a Boost item, trying to do in this way :
TrophyFormSet = inlineformset_factory(db.gameInfo, db.boost, extra=1)
formset = TrophyFormSet()
Here are my questions :
1 - When rendered, the combo box for "Creator" shows a list of "db.userInfo" (literally)! I want this to display db.userInfo.auth.username that is already in the database... how to do this?
2 - In this way, where is my "db.gameInfo" to choose?
thank you! =D
======
czarchaic answered my question very well!
But now I need just a little question:
When I use the modelform to create a form for the boost_trophy model :
class boost_trophy(models.Model):
boost = models.ForeignKey(boost)
trophy = models.ForeignKey(gameTrophyInfo)
# 0 - Obtiveis
# 1 - Requisitos minimos
type = models.IntegerField(default=0)
class gameTrophyInfo(models.Model):
game = models.ForeignKey(gameInfo)
name = models.CharField(max_length=500)
desc = models.CharField(max_length=500)
type = models.CharField(max_length=20)
It works nice, but I want the form to show in the "game" box only a really small set of items, only the: gameTrophyInfo(game__name="Game_A") results. How can I do this?
If I understand you correctly:
To change what is displayed set the model's __unicode__ function
class userInfo(models.Model):
#model fields
def __unicode__(self):
return self.auth.username

Categories