Cascade deletion in Django models with GenericForeignKey - django-models

I have the following problem with Django.
class UserProfile(Model):
inventory = models.M2M(InventoryItem)
class InventoryItem(Model):
item = GenericForeignKey()
class Equipment(Model):
base = GenericForeignKey()
Every user can have many items. Inventory item can point to equipment, materials and so on, but in this case it points to Equipment model. Equipment model has a relation to either Weapon or Armour or Accessory.
I need to remove a specific item from user's inventory.
UserProfile.objects.get(pk=1).inventory.objects.all()[0].delete()
** This also deletes equipment and weapon/armour/accessory objects related which is not intended. **
I have already added on_delete=DO_NOTHING on all foreign keys, but I do not see such option possible on GenericForeignKeys. What's the solution?

UserProfile.objects.get(pk=1).delete()
it looks like you're deleting the UserProfile, but not the specific item

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

Two foreignkeys for one field in djangomodel

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.

Django Queryset Construction and Update

I have a model with 2 foreign keys to the same model.
class Team(models.Model):
name= models.CharField()
class Game(models.Model):
team_1= models.ForeignKey(Team)
team_2= models.ForeignKey(Team)
date = models.DateTimeField()
team_1_post_game_rating = models.DecimalField()
team_2_post_game_rating = models.DecimalField()
If there is a result, a calculation is done updating the rating based on the result and the rankings of both teams. No problems so far, except if a result is edited after other games have been played.
What i need to be able to do (In the most efficient way possible) is find all the games and update the rankings for all teams that were played by either team subsequent to the game that was edited and any team that those teams played and so on.
I could probably do it using a sub query and values list and iterating on the results but of course Id rather find a nice clean way to construct it dynamically and get away without my database going into meltdown.

Best way to structure my shopping database?

Right now my database has the following (simplified) format:
ShoppingList
{
List<ListProduct> listProducts
}
ListProduct
{
int quantity
Product product
}
Product
{
information about the overall product...
List<StoreProduct> StoreProduct
}
StoreProduct
{
information about the specific product and the store
}
In general, a shoppinglist contains a list of listproducts which each contains their quantity and their product which each contains a list of storeproducts.
This all works great - however, in my shoppinglist I wanna keep track of which storeproducts were purchased. Now I can't just add a "purchased" boolean to my storeproducts since they are used across multiple shopping lists (static information).
I thought of adding a purchasedProduct property of ListProduct which would be set to the purchased storeProduct and otherwise be null.
However I'm unsure as to whether there exists any better solutions? My schema is complex already so I'd don't want to make it even more complex if it isn't necessary.
UPDATE:
Here's my customer table:
Customer
{
List<ShoppingList> shoppingLists
}
Why don't you make a new table with something like CustomerID column references to Customer and another column references StoreProduct. Use that to store all the purchased product. I would suggest you to list the Schema related to Customer for this kind of question.

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();

Resources