Get objects that are foreign key - django

I need ot get objects that are foreign keys. Example
class City(models.Model):
.....
class User(models.Model):
city = models.ForeignKeu(City)
.......
Can i get only that cities which are Foreign key to model User with django orm or mysql?

Yes you can, it's all in the Documentation:
https://docs.djangoproject.com/en/1.6/ref/models/querysets/
Provide a readable backward reference to the city model (in your User model change city to this one):
city = models.ForeignKey(City, related_name='user')
Then
cities = City.objects.select_related('user').filter(user__city__isnull=False).all()

Related

Django Model M2M Relationship to 2 other models from the same model

Here in my problem, I have a User model, in which a user (login) can be from the “Supplier” company or from “Customer” company.
It is a M2M relationship for both sets of tables: User-Customer and User-Supplier.
Can I link them this way:
company = models.ManyToManyField(Customer, Supplier, on_delete=models.PROTECT, related_name='Users')
enter image description here
Thanks!!
You can't do that.
A better approach will be if you use a Company model with a type of Supplier and Customer you can create an enum for this because you are using the same fields in both of your models so its good to have a type in a single model.
How to make enum in model with TextChoices
Company:
name
address
contact name
type
then in your User model
company = models.ManyToManyField(Company, on_delete=models.PROTECT, related_name='Users')
make more sense this way.

Django union two tables into single model

I have an external database which I can't modify in any way (read-only). It has three tables - Company (id), CompanyContact (company_id, contact_id), Contact (id, company_id).
Basically, Contact has a nullable foreign-key to Company table and it works as many-to-one, but if company_id is null, I have to look into CompanyContact table, which is many-to-many kind relationship.
How can I combine these two tables (Contact and CompanyContact) into one model - Contact? In other words, how can I get all contacts for a given company?
In SQL that would be something like:
select contact.id from contact where company_id = XXX
union
select contact_id from companycontact where company_id = XXX
Django models:
class Company(models.Model):
uuid = models.CharField(max_length=36, primary_key=True, db_column='id')
class Meta:
managed = False
class Contact(models.Model):
uuid = models.CharField(max_length=36, primary_key=True, db_column='id')
company = models.ForeignKey(Company, db_column='company_id')
class Meta:
managed = False
I don't have a model for CompanyContact. And there is nothing to show in views because that basically is my question, how to get contacts for a given company.
The original tables in your database are not properly structured. It's incorrect that the contact field should have a company_id field. That needlessly complicates all queries (raw SQL or Django) because an additional check is needed on the contact_id field.
On the other hand it's perfectly legit for two entities in a many to many relationship to have exactly one mapping instead of many. So there isn't one clear answer to this question. I suppose your best bet would be to add a ManyToMany field as well. I am making this suggestion purely on the fact that you say the data is read only
class Contact(models.Model):
uuid = models.CharField(max_length=36, primary_key=True, db_column='id')
company = models.ForeignKey(Company, db_column='company_id')
companies = models.ManyToManyField(Company, related_name='companies')
class Meta:
managed = False

Django Form foreign key relationship

I'm building a simple application to collection emp infor and emp address.
I have 2 tables.
class Employee(models.Model):
fname = models.CharField(max_length=100)
lname = models.CharField(max_length=100)
class EmployeeAdd(models.Model):
emp = models.ForeignKey(Employee)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
zip = models.CharField(max_length=5)
Now, Im planning to create 2 form EmpForm and EmpAddressForm.
Is it possible to display both these form together in one single page and collect both emp and empaddr information?
Have you looked at the Django documentation about Model Forms? It has a section on inline formsets that might help you.
Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key

django manytomany through

If I have two Models that have a manytomany relationship with a through model, how do I get data from that 'through' table.
class Bike(models.Model):
nickname = models.CharField(max_length=40)
users = models.ManyToManyField(User, through='bike.BikeUser')
The BikeUser class
class BikeUser(models.Model):
bike = models.ForeignKey(Bike)
user = models.ForeignKey(User)
comment = models.CharField(max_length=140)
And I would add a user to that bike (presuming I have a myBike and a myUser already)
BikeUser.objects.create(bike = myBike, user = myUser, comment = 'Got this one at a fancy store')
I can get all the users on 'myBike' with myBike.users.all() but how do I get the 'comment' property?
I would like to do something like
for myBikeUser in myBike.users.all():
print myBikeUser.comment
The through table is linked by standard ForeignKeys, so you do a normal ForeignKey lookup. Don't forget that there's a comment for each bikeuser, ie one for each bike/user pairing.
for myBikeUser in myBike.bikeuser_set.all():
print myBikeUser.comment, myBikeUser.user.first_name

Django Relational database lookups

I cant figure out how to do relationships.
I have a products model and a stores model.
A product has a foreign key to the stores.
So i would like to get the product name, and the store name in the same lookup.
Since the products model is:
class Products(models.Model):
PrName = models.CharField(max_length=255)
PrCompany = models.ForeignKey(Companies)
And the company model is:
class Companies(models.Model):
ComName = models.CharField(max_length=255)
How do i make django return ComName (from the companies model) when i do:
Prs = Products.objects.filter(PrName__icontains=ss)
Assuming you get results:
Prs[0].PrCompany.ComName # Company name of the first result
If you want all the company names in a list:
company_names = [product.PrCompany.ComName for product in Prs]