Dynamic generation ForeignKey fields on admin page django - python

I have models:
class CompanyInfo(models.Model):
name = models.CharField('Имя компании',max_length=250)
class Staff(models.Model):
company_name = models.ForeignKey(CompanyInfo)
date = models.DateField( )
name = models.CharField( max_length=30, )
class Relation(models.Model):
company_name = models.ForeignKey(CompanyInfo)
who = models.ForeignKey(Staff, related_name="who")
with_whom = models.ForeignKey(Staff, related_name="with_whom")
info = models.CharField( max_length=30, )
How I can create dynamic generation fields for WHO and WITH_WHOM form element on the admin-page? I chose COMPANY_NAME, and fields WHO and WITH_WHOM that show only people from that company.

Can you please elaborate in a bit more detail on what you mean by dynamic generation fields? Otherwise, I'm afraid it's a bit difficult to help you because it's not really clear what your problem is.
Besides that, let me tell you that your model design is rather odd, especially your Relation model. If you want to establish a many-to-one relationship between two instances of the same model (I think that's what you are trying to accomplish here), then you should write it like that and get rid of your Relation model:
class Staff(models.Model):
with_whom = models.ForeignKey('self')

Related

How to get list of all objects associated with a foreign key in Django

Not super experienced with Django so I apologize if this is trivial. Say I had a category instance and I wanted to get access to all of the content objects that I have previously added to my foreign key. How would I do so?
class Organization(models.Model):
id = models.CharField(primary_key=True, max_length=200, default=uuid4, editable=False, unique=True)
name=models.CharField(max_length=200,unique=True)
phoneNumber=models.CharField(max_length=20)
logo=models.CharField(max_length=100000) # storing this as base 64 encoded
location=models.CharField(max_length=200)
class Category(models.Model):
categoryName=models.CharField(max_length=300, unique=True, primary_key=True)
associatedOrganizations=models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='associatedOrgs',null=True,blank=True)
associatedContent=models.ForeignKey(Content, on_delete=models.CASCADE,related_name='associatedContent',null=True,blank=True)
associatedMeetingNotices=models.ForeignKey(MeetingNotice,on_delete=models.CASCADE,related_name='associatedMeetingNotices',null=True,blank=True)
For example:
say I had the following
healthcareCategory=models.Category.objects.get(pk="healthcare")
and I wanted to access all Organizations related to healthcare, what should I do?
This?
healthcareCategory.associatedOrganizations.all()
You are close. You may want to change that related name from associatedOrgs to be associatedorgs to follow more closely to the django coding style. Documentation on this has a few examples.
healthcare_category = Category.objects.get(pk="healthcare")
organizations = healthcare_category.associatedorgs.all()
The answer by #AMG is correct. If you had not defined a related_name for associatedOrganizations you could simply do
organizations = Organization.objects.filter(category__pk='healthcare')
But I think there is another issue. Am I correct in saying that an Organization can have only one Category, but a Category can have many Organizations?
If so, then I think the ForeignKey in your model is in the wrong place.
class Organization(models.Model):
id = models.CharField(primary_key=True, max_length=200, default=uuid4, editable=False, unique=True)
name=models.CharField(max_length=200,unique=True)
phoneNumber=models.CharField(max_length=20)
logo=models.CharField(max_length=100000) # storing this as base 64 encoded
location=models.CharField(max_length=200)
# The ForeignKey should be here:
category = ForeignKey(Category, on_delete=models.CASCADE)
class Category(models.Model):
categoryName=models.CharField(max_length=300, unique=True, primary_key=True)
# remove this
# associatedOrganizations=models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='associatedOrgs',null=True,blank=True)
...
The ForeignKey is a ManyToOneField so you place it in the model that will be the many, and you link it to the model that will be the one.
Now you can find all organizations within the healthcare category like this:
organizations = Organization.objects.filter(category='healthcare')

Using multiple columns as ForeignKey to return in another table

I'm new to Django so I make 3 simple tables to return a WishList. The thing is that I want whenever user asks for WishList, his/her user_id is used to make a SELECT query to return his/her own WishList. And I want to get product title and product url from my WishList table. I'm using to_field but with that way I only can get product title back. I don't know much about Django so help me!
Product
class Product(models.Model):
class Meta:
unique_together = (('id', 'title'),)
title = models.CharField(max_length=200, unique=True,
help_text='Name of the product')
url = models.CharField(max_length=300, default='',
help_text='Url of the product')
def __str__(self):
return 'Product: {}'.format(self.title)
WishList
class WishList(models.Model):
class Meta:
unique_together = (('user', 'product'),)
user = models.ForeignKey(fbuser,
on_delete=models.CASCADE,
help_text='Facebook user',
to_field='user_id')
product = models.ForeignKey(Product, to_field='title', db_column='title',
on_delete=models.CASCADE)
def __str__(self):
return 'WishList: {}'.format(self.user)
It's not a good practice to override to_field to another field different than your model.pk unless you have a really good reason and you know what you are doing (definitely not the case right now).
So after you read the docs, you will know that in order to get wishlisht related to a user, you can use the ForeignKey reverse relation to get all related wishlists for a user.
user_wishlists = my_user.wishlist_set.all()
#Because we know that you want to access the wishlist.products
#in order to optimize things (in terms of db queries)
#you can add and .select_related('product')
#e.g, user_wishlists = my_user.wishlist_set.all().select_related('product')
#now follow the wishlist.product foreign key to access the related product for every wishlist
for wishlist in user_wishlists:
product = wishlist.product
print (product.id, product.title, product.url)
Now after you read a little bit more of the documentation
you will notice that your WishList model is in fact an intermediate model for a ManyToMany relation between User and his wished products, then you will know that you can define a M2M field between user and products via WishList like so:
class FbUser(models.Model):
#...
wished_products = models.ManyToManyField(
Product,
through='WishList',
through_fields=('user', 'product')
)
#and now accessing user wished products would be easy as:
user_wished_products = my_user.wished_products.all()
for product in user_wished_products:
print (product.id, product.title, product.url)

Creating many to many relation with AUTH_USER_MODEL in django via intermediary model

I am trying to create the following models. There is a ManyToMany relation from Entry to AUTH_USER_MODEL via the EntryLike intermediate model.
class BaseType(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
creation_time = models.DateTimeField(auto_now_add=True)
last_update_time = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Title(BaseType):
text = models.CharField(max_length=100)
description = models.TextField()
class EntryLike(BaseType):
entry = models.ForeignKey(Entry)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
class Entry(BaseType):
title = models.ForeignKey(Title, on_delete=models.PROTECT)
text = models.TextField()
user = models.ForeignKey(settings.AUTH_USER_MODEL)
liked_by_users = models.ManyToManyField(settings.AUTH_USER_MODEL, through='EntryLike', through_fields=('entry', 'user'))
Running migrations on the above model scheme throws the error: AttributeError:'str' object has no attribute 'meta'.
Any help in resolving this error would be highly appreciated. Am new to Django & Python, but not to Web Development.
The issue is that settings.AUTH_USER_MODEL is almost certainly not a model instance. It's probably a string that constrains the choices another model can make - settings would be a strange place to leave a model definition.
To do a MTM between the user model and your field above you need need to do:
from django.contrib.auth.models import User
class Entry(BaseType):
title = models.ForeignKey(Title, on_delete=models.PROTECT)
text = models.TextField()
user = models.ForeignKey(User)
def __str__(self):
return self.title
I've added the str function so that it gives a more sensible return when you're manipulating it in admin/shell.
I'd also question whether you need the second set of fields (removed here), as you can use select related between the Entry and EntryLike join table, without any duplication of the fields - you can probably go that way, it's just a bit unnecessary.
Lastly, I'd note that the way I'm using it above just uses the default User object that comes with Django - you may wish to customise it. or extend the base class as you've done here with your own models' base class.
(All of this is predicated on AUTH_USER_MODEL not being a model instance - if it is, can you post the model definition from settings.py? )

Django field not populating in admin

I have just added a new field to one of my models, I have deleted and recreated my database, but when I enter info into the new field, nothing appears to have saved for that field, but the others have.
The field looks like this
class Author(models.Model):
display_name = models.CharField(unique=True,max_length=30)
first_name = models.CharField(max_length=15)
phone = models.CharField(max_length=15, blank=True)
twitter_handle = models.CharField(max_length=20, blank=True)
And I have included it into the fields list in forms.py
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ['display_name','first_name','twitter_handle','phone']
Any ideas what could be causing this?
Any help appreciated
The code looks fine. Can you provide the rest of your code?
Some databases require that you define a primary_key - depends on your other PKs in the model
Try adding primary_key=True to your display_name field and see if it helps
FIXED
Due to a complex interaction between two forms that are submitted at the same time with various validation constraints, I manually populate the models from the forms in a views function, and I had forgotten to add the twitter_hanle to this, oops sorry, hopefully this will help if someone makes the same oversight.

django having multiple one many to many relations that references same model

i have a model that is having multiple many to many relation to another model it is as follows:
class Match(models.Model):
"""Model docstring"""
Match_Id = models.AutoField(primary_key=True)
Team_one = models.ManyToManyField('Team',related_name='Team one',symmetrical=False,)
Team_two = models.ManyToManyField('Team',related_name='Team two',symmetrical=False,)
stadium = models.CharField(max_length=255, blank=True)
Start_time = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
Rafree = models.CharField(max_length=255, blank=True)
Judge = models.CharField(max_length=255, blank=True)
winner = models.ForeignKey('Team', related_name='winner',to_field='Team_Name')
updated = models.DateTimeField('update date', auto_now=True )
created = models.DateTimeField('creation date', auto_now_add=True )
what is the best way to implement model like this ?. all though django does not throw any errors when passing the model sql once syncdb is excuted it throws up errors saying there is no unique constraint matching given keys
Are you sure Team_one and Team_two should be ManyToMany fields? Surely, a match only has a single team on each side - in which case these should both be ForeignKeys.
Using spaces in related_name attribute makes me uneasy, but I think the real problem is connected to the use of to_field attribute on the winner field. As far as I know you can set database relations only to unique fields. It doesn't really make sense to relate to another object using a field that may not be unique.
I'm not sure what do you want to achieve by connecting through this particular field. You usually connect models using primary key fields. This still allows you to access any other field on the related object.

Categories

Resources