Django Query with getting all the item in manytomanyfield - django-models

This is my models:
class Persons(models.Model):
name = models.CharField(max_length=50)
class Group(models.Model):
members = models.ManyToManyField(
Persons,
related_name='group_members'
)
I am trying to get all the group members like this:
p = Persons.objects.select_related('group_members').values('id')
and it returns all the Person id, this is the problem.
I want only person id who are in any of the group members..
Can anyone help me in this case?

i suggest to make a title for the group like this
class Group(models.Model):
name = models.CharField(max_length=20)
and then make a group for example name it 'GOT fans', then assign it to multiple users.
then select all the 'Persons' in that particular group like this
gotFansIDS = Group.objects.filter(name="GOT fans").values('id')

Related

Filtering down through multiple ForeignKey relations in django

I am trying to get down through multiple-foreign key relationship where each Hotel has many Rooms, each Room has many Rateplans, each Rateplan has many Prices.
It resembles Christmas tree if you think about it:
Hotel
v
Room
v
Rateplan
v
Prices
How can I execute query that will return hotels in certain hotel_city on certain price_date, certain price_price and certain price_availability? (just like Expedia or booking.com query)
For example:
Hotel.objects.filter(city='Beirut').filter(room__name=Room.objects.filter(rateplan__name=Rateplan.objects.filter(prices__availability=Prices.objects.filter(availability=1))))
I have looked into django complex queries documentation and annotate/aggregate but couldn't wrap my head around it.
My models below:
class Hotel(models.Model):
name = models.CharField(max_length=64)
city = models.CharField(max_length=64, default='Warsaw')
class Room(models.Model):
hotel_id = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name='room')
name = models.CharField(max_length=64, default='Double')
class Rateplan(models.Model):
room_id = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='rateplan')
name = models.CharField(max_length=64, default='Standard')
class Prices(models.Model):
rateplan_id = models.ForeignKey(Rateplan, on_delete=models.CASCADE, related_name='prices')
date = models.DateField()
price_1 = models.DecimalField(null=False, max_digits=7, decimal_places=2)
price_2 = models.DecimalField(null=False, max_digits=7, decimal_places=2)
availability = models.SmallIntegerField()```
You can use __ to filter the values you need across relationships
There are good examples in the documentation
Hotel.objects.filter(
city=your_city,
room__rateplan__prices__date=your_date,
room__rateplan__prices__price_1=your_price,
room__rateplan__prices__availability=your_availability,
).distinct()

Get Contact Emails of Currently Active Account as List

Given: A Salesforce user is viewing an account page.
Desired Output: All Emails of Contacts related to the Account currently viewed as a List object.
My code:
SELECT Email FROM Contact WHERE Id IN (SELECT ContactId FROM AccountContactRelation WHERE AccountId = ApexPages.CurrentPage.getParameters().get('id'))
This does not retrieve any results. When using a fixed number instead of ApexPages.CurrentPage.getParameters().get('id'), the Emails are correctly returned.
I'm sort of new to Apex. Could anyone point out what I am doing wrong?
To achieve the desired output you need to use SOQL variable injection.
You can do this by creating a variable first and then referencing the variable inside the SOQL using : and the variable name:
String theAccountId = ApexPages.CurrentPage.getParameters().get('id');
List<Contact> theContacts = [SELECT Email FROM Contact WHERE Id IN (SELECT ContactId FROM AccountContactRelation WHERE AccountId = :theAccountId)];
You can use a static query with a bind variable to retrieve the correct results.
Additionally, the Contact object contains an AccountId field of its own. Therefore, depending on your setup, you may be able to eliminate your subquery. You may also want to filter out Email fields that are empty, since Email is not a required field.
The complete result could look something like this:
String accountId = ApexPages.CurrentPage.getParameters().get('id');
List<Contact> accountContactsEmailList = [
SELECT
Email
FROM
Contact
WHERE
Email != ''
AND AccountId = :accountId
];
for (Contact contact : accountContactsEmailList) {
System.debug(contact.Email);
}

Trying to make a small inventory app in Django

I am trying to make a small inventory app in a Django app. I want to be able to see the stock on hand, where it is (between two places and all together), purchase to add to inventory, and sell to reduce inventory. Tracking sales would be nice. So all in all, there are about five things I would like to do. To track the location, I was thinking of listing warehouse one as 1 and two as 2, and could query WHERE field = 1, but if I have the same product in two places, I would run into an issue. I also don't know the best way to approach it. Reading through post here, I see some people saying to just track sales, and total them in a flat db, others to remove from the db, but that would lead to discrepancies. This is my model.py so far, just really stabbing at the dark here, looking for some guidance.
from django.db import models
class Product(models.Model):
product_ID = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
type = (
('WHT' , 'White Wine'),
('RED' , 'Red Wine'),
('SPRT', 'Spirits'),
('BR' , 'Beer'),
)
size = (
('12' , '12oz'),
('16' , '16oz'),
('375' , '375mL'),
('750' , '750mL'),
('1' , '1L'),
)
amount_per_case = models.IntegerField()
warehouse = (
(1 , 'One'),
(2 , 'Two'),
)
on_hand = models.IntegerField()
class Store(models.Model):
store_ID = models.IntegerField(primary_key=True)
store_name = models.CharField()
store_type = (
('Supermarket', 'Supermarket'),
('Liquor Store', 'Liquor Store'),
)
store_address = models.CharField()
store_phone = models.CharField()
store_contact = models.CharField()
class Vendor(models.Model):
vendor_ID = models.IntegerField(primary_key=True)
vendor_name = models.CharField()
vendor_address = models.CharField()
vendor_phone = models.CharField()
vendor_contact = models.CharField()
class Sale(models.Model):
sale_date = models.DateField()
sale_product = models.ForeignKey(Product)
You should make a Warehouse model and create a many-to-many relationship between Product and Warehouse, using the through option to specify another model to hold relationship details called something like WarehouseProduct, in which you store the counts. See this section of the docs, and the following section.
P.S. You can do much the same thing to associate sales with particular stores, which seems to me to be something that would probably be of interest to you, as well.

Django many-to-many query for zero records in related model

Using the standard Django example model for M2M relationships. I would like to return a list of Person (people) that don't have a Membership (ie. no related records in the Membership table. How would I go about doing this? Is anybody able to point me in the right direction?
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
Thank you.
Person.objects.filter(membership__isnull=True)
https://docs.djangoproject.com/en/1.4/ref/models/querysets/#isnull

Need to order by properties in the reference property, any good solution?

Say I have 2 kind:
class Account(db.Model):
name = db.StringProperty()
create_time = db.DataTimeProperty()
last_login = db.DateTimeProperty()
last_update = db.DataTimeProperty()
class Relationship(db.Model)
owner = db.ReferenceProperty(Account)
target = db.ReferenceProperty(Account)
type = db.IntegerProperty()
I want to get the equivalence of following query:
SELECT target
FROM Relationship
WHERE owner = :key AND type = :type
ORDERBY target.last_login DESC
How to do that?
reference: http://www.mail-archive.com/google-appengine#googlegroups.com/msg15878.html
There's no equivalent for that query in datastore. Some points:
You can't select a single property. SELECT is always SELECT * (you select a whole entity).
You can't do joins. You need to denormalize your models to fit the queries you will perform, or perform multiple queries.
So to achieve your goal, you need to have last_login stored in Relationship, or have a 3rd model to serve as index for that specific query.

Resources