Two foreignkeys for one field in djangomodel - django-models

I'm having some trouble wrapping my head around this problem I've made for my self.
I have these two customer models, with some similar and some different fields. I want either of these two to be assigned as ForeignKey to a field in my projectclass.
The idea is, that when the user creates a project, the user can choose from all customers and assign from both private and company customers for that particular field, but not having to specifiy anywhere beforehand what kind of customer it is.
Private customer
class PrivateCustomer(models.Model):
.. fields
Company Customer
class CompanyCustomer(models.Model):
...
Project
class Project(models.Model):
customer = model.ForeignKey(PrivateCustomer,CompanyCustomer)
Can I make a join of the two for that particular field, on the fly, as instance occurs or should I just drop the seperation between the two customer classes and handle this through UI inputs?

How about having both fields with condition null = True
class Project(models.Model):
privateCustomer = models.ForeignKey(PrivateCustomer, null = True)
companyCustomer = models.ForeignKey(CompanyCustomer , null = True)
And then from your views, you can handle them easily.

Related

How do i search two collection on the same _id

I'm working on a project of mine and I have encountered a problem. Let's suppose that we have three classes (models) respectively Person, Shop, Transaction: the first and second one (Person and shop) are both interacting by creating and pushing in arrays an instance of Transaction. They all look as follows :
Person
{
firstName:String,
lastName:String,
transactions:[ref:Transaction],
...other properties...
}
Shop
{
name:String,
customers:[ref:Person]
transactions:[ref:Transaction],
...other properties...}
}
Transaction
{
from:ref,//id of person||shop
to:ref, //id of person||shop
amount:float
...other properties...
}
Now when some one opens and ask the app for the balance (money they have) he/she should see a list of transaction and the name of the either of the two other class... so normal populate or lookup won't do cause in the two different collection the id's might be the same so one of the way I wanted to address it was by creating an extra id that would be used when creating any of the Person and Shop instance thus any will have its own id (example: person.id-> 1,shop.id->2). But we would do first a query on id in the Person collection and then if this result is null we would then perform the second query on id in the Shop collection... I don't really like this solution so if anyone reading this have a solution please share it with me ... Thanks in advance
Edit: The Person instances may also send transactions to one an other

Convert three modelsto one single query django query

This are my model with some of the fields:
class Advertisers(models.Model):
account_manager_id = models.ForeignKey(AccountManagers, on_delete=models.CASCADE,null=True, db_column='account_manager_id',related_name="advertisers")
class AdvertiserUsers(models.Model):
user_id = models.OneToOneField('Users', on_delete=models.CASCADE,null=True,db_column='user_id', related_name='advertiser_users')
advertiser_id = models.ForeignKey('Advertisers', on_delete=models.CASCADE,null=True,db_column='advertiser_id', related_name='advertiser_users')
class Users(models.Model):
email = models.CharField(unique=True, max_length=100)
I want Id's, user ids and email of all advertisers.
Id's of all user:-
advertiser_ids = advertisers.objects.all() # can get id from here
find user_ids of advertiser_ids:
user_ids = AdvertiserUsers.objects.filter(advertiser_id__in=advertiser_ids) # can get user_id from here
find id and email using this query:
user_ids = Users.objects.filter(id__in=user_ids) # can get email from here
How to make it shorter like directly querying from Advertisers i will be able to get Users models email.
Thankyou in advance
You can filter with:
Users.objects.filter(advertiser_users__advertiser_id__isnull=False).distinct()
The .distinct() [Django-doc] will prevent returning the same Users multiple times.
You can annotate the User objects with the Advertisers primary key, etc:
from django.db.models import F
Users.objects.filter(advertiser_users__advertiser_id__isnull=False).annotate(
account_manager_id=F('advertiser_users__advertiser_id__account_manager_id'),
advertiser_id=F('advertiser_users__advertiser_id')
)
The Users objects that arise from this have a .email attribute (and the other attributes that belong to a Users object), together with a .account_manager_id and an .advertiser_id. That being said, this is probably not a good idea: the way you have modeled this right now, is that a Users object can relate to multiple Advertisers objects, so it makes not much sense to add these together.
You can for each user access the related Advertisers with:
myusers = Users.objects.filter(
advertiser_users__advertiser_id__isnull=False
).prefetch_related(
'advertiser_users',
'advertiser_users__advertiser_id'
).distinct()
for user in myusers:
print(f'{user.email}')
for advuser in user.advertiser_users.all():
print(f' {advuser.advertiser_user.pk}')
Note: normally a Django model is given a singular name, so User instead of Users.
Note: Normally one does not add a suffix _id to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be account_manager_id, instead of account_manager.
Advertisers.objects.all().values_list('id','account_manager_id','advertiser_users__user_id',advertiser_users__user_id__email)

Retrieving data from referenced key table - Laravel-4

The structure of concerning tables is as follows (MySQL):
//Table Name : team
tid PK
team_name (varchar)
//Table Name : fixture
fid PK
home_team_id FK |_ both referenced to 'tid' from 'team' table
away_team_id FK |
My aim is to retrieve the team names. Considering this structure, I think I'll have to retrieve home_team_id and away_team_id and then do something like
Fixture::where('tid','=',$home_team_id)->get();
My question is, is this the correct way to accomplish what I aim to do?
and
should this be done from the controller? (if so, then I'll have to do two queries from same function)
First, rather than having your primary keys be tid and fid, just keep them both as id. This is not only best practice, but will allow you to more easily use Laravel's Eloquent ORM as it by default assumes your primary key column is named id.
Second thing, make sure your table names are in plural form. Although this is not necessary, the example I'm about to give is using Laravel defaults, and Laravel assumes they are in plural form.
Anyway, once you've 'Laravelized' your database, you can use an Eloquent model to setup awesome relationships with very minimal work. Here's what I think you'd want to do.
app/models/Team.php
class Team extends Eloquent {
// Yes, this can be empty. It just needs to be declared.
}
app/models/Fixture.php
class Fixture extends Eloquent {
public function homeTeam()
{
return $this->belongsTo('Team', 'home_team_id');
}
public function awayTeam()
{
return $this->belongsTo('Team', 'away_team_id');
}
}
Above, we created a simple model Team which Laravel will automatically look for in the teams database table.
Second, we created model Fixture which again, Laravel will use the fixtures table for. In this model, we specified two relationships. The belongsTo relationship takes two parameters, what model it is related to, in both cases here they are teams, and what the column name is.
Laravel will automatically take the value in away_team_id and search it against the id column in your teams table.
With just this minimal amount of code, you can then do things like this.
$fixture = Fixture::find(1); // Retrieves the fixture with and id of 1.
$awayTeam = $fixture->awayTeam()->first(); // var_dump this to see what you get.
$homeTeam = $fixutre->homeTeam()->first();
Then you can proceed as normal and access the column names for the tables. So say you have a 'name' column in the teams table. You can echo out the the home team name from the fixture like so.
$fixture = Fixture::find(1); // Get the fixture.
echo $fixture->homeTeam->name;
It's nearly 2AM, so there might be an error or two above, but it should work.
Make sure you check the docs for Eloquent, especially the bits relating to relationships. Remember to name your columns and tables in the way Laravel wants you to. If you don't, there are ways to specify your custom names.
If you want to get even more fancy, you can define the inverse relationship like this on your Team model.
app/models/Team.php
class Team extends Eloquent {
public function fixturesAtHome()
{
return $this->hasMany('Fixture', 'home_team_id');
}
public function fixturesAway()
{
return $this->hasMany('Fixture', 'away_team_id');
}
}
Then to get all of a particular team's home fixtures...
$team = Team::find(1); // Retreive team with id of 1;
$homeFixtures = $team->fixturesAtHome();

objectify query filter by list in entity contains search parameter

in an app i have an entity that contains a list of other entities (let's say an event holding a list of assigned employees)
using objectify - i need to find all the events a particular employee is assigned to.
is there a basic way to filter a query if it contains the parameter - kind of the opposite of the query in
... quick pseudocode
findAll(Employee employee) {
...
return ofy.query(Event.class).filter("employees.contains", employee).list();
}
any help would be greatly appreciated
i tried just doing filter("employees", employee) after seeing this http://groups.google.com/group/objectify-appengine/browse_thread/thread/77ba676192c08e20 - but unfortunately this returns me an empty list
currently i'm doing something really inefficient - going through each event, iterating through the employees and adding them to a new list if it contains the given employee just to have something that works - i know this is not right though
let me add one thing,
the above query is not actually what it is, i was just using that because i did not think this would make a difference.
The Employee and Events are in the same entity group with Business as a parent
the actual query i am using is the following
ofy.query(Event.class).ancestor(businessKey).filter("employees", employee).list();
unfortunately this is still returning an empty list - does having the ancestor(key) in there mess up the filter?
solution, the employees field was not indexed correctly.
I added the datastore-indexes file to create a composite index, but was testing originally on a value that I added before the employees field was indexed, this was something stupid i was doing - simply having an index on the "business" field and the "employees" field fixed everything. the datastore-indexes file did not appear to be necessary, after deleting it and trying again everything worked fine.
Generally, you do this one of two ways:
Put a property of Set<Key<Employee>> on the Event
or
Put a property of Set<Key<Event>> on the Employee
You could also create a relationship entity, but if you're just doing filtering on values with relatively low counts, usually it's easier to just put the set property on one entity or the other.
Then filter as you describe:
ofy.query(Event.class).filter("employees", employee).list()
or
ofy.query(Employee.class).filter("events", event).list()
The list property should hold a Keys to the target entity. If you pass in an entity to the filter() method, Objectify will understand that you want to filter by the key instead.
Example :
/***************************************************/
#Entity
#Cache
public class News {
#Id Long id;
String news ;
#Index List<Long> friend_list = new ArrayList<Long>();
// My friends who can see my news , exemele : friend_list.add(id_f1); friend_list.add(id_f2); friend_list.add(id_f3);
//To make an operation on "friend_list", it is obligatory to index it
}
/*************************************************/
public News(Long id_f){
List<Long> friend_id = new ArrayList<Long>();
friend_id.add(id_f);
Query<Nesw> query = ofy().load().type(News.class).filter("friend_list in",friend_id).limit(limit);
//To filter a list, just after the name of the field you want to filter, add "IN".
//here ==> .filter("friend_list in",friend_id);
// if friend_list contains "id_friend" ==> the query return value
.........
}

Linq to Entities (join query) - WPF - 4 layer application

I'm new to this all and I like to know how experienced programmers handle the following situation
Let's say I have a table "Supplier" with some common fields and also fields MailingAddress, BillingAddress which are 2 key fields to link to another table "Address"
TB Supplier
Id = 1
Name = MyNameFoo
MailingAddressId = 100
BillingAddress = 101
TB Address
Id = 100
Street = MailingStreetFoo
City = MailingCityFoo
Id = 101
Street = BillingStreetFoo
City = BillingCityFoo
I have a 4 layer application solution:
project xyz.WPF which hold al my WPF windows to presentate the data to the user (Listbox with Binding)
project xyz.Business : in between WPF and DataAccess (SupplierB.vb, AddressB.vb)
project xyz.DataAccess.SqlServer : data layer (SupplierDAL.vb, AddressDAL.vb)
project xyz.Entities : to store my entity classes, each representing a table and just holding properties. I use this to pass from one layer to another (SupplierE.vb, AddressE.vb).
SupplierDAL class gets data from SQL Server and returns a "List(Of SupplierE)" to SupplierB class which return this "List(Of SupplierE)" to the WPF where it is bound to listbox -> Listbox.ItemsSource = SupplierB.GetAllSuppliers().
Now I can get all suppliers and show them in a WPF window in a listbox (or datagrid, ...) Also I can get all addresses and show them.
But at some point I want to get all the addresses (Mailing, Billing) for one Supplier. I know how to write my query with linq (join the 2 tables) but what do I have to do with the result of it. It is not a SupplierE nor a AddressE; it's a combination of the two. I want the result to be an object that I can pass around the layers, just like SupplierE.vb, AddressE.vb. Of course I could make another entity like SupplierAddressesE.vb; problem solved but in my real live solution I have dozens of join queries with joins between several different tables (not just Supplier, Address).
So a lot of tables, a lot of join query results; does this means I have to make a entity object (xxxE.vb) for each different join query or is there another way we can do this in a 4-tier layer application with Linq to Entities?
Thanks for any reply which can direct me to a good approach for this situation
Luc
If you are lazy loading the entities, then your supplier entity should have the attached address entity for each of Mailing/billing. Why not just have create a proper Supplier class that has properties for Mailing/Billing that are Address classes as opposed to Ids?

Resources