How to filter a Django ORM query using an annotation against a model attribute? - django-orm

I have a Model with an attribute containing an Int capacity, and a FK relationship to manage the utilisation, as follows:
class Container(Model):
objects = ContainerManager()
capacity = PositiveSmallIntegerField(default=1)
class Item(Model):
container = ForeignKey('Container', related_name='items'
The Manager needs to find containers that have spare capacity i.e. the number of Items associated with the Container. I am using an annotation to count the Items, but cannot work out how to compare this with the capacity i.e. something like this..
get_queryset().annotate(utilisation=Count('items').filter(capacity__gt=utilisation)
Is this possible in one query?

So, I'm answering my own question in case it helps others.. the solution is to use an F() expression..
get_queryset().annotate(utilisation=Count('items').filter(capacity__gt=F(utilisation))

Related

Is there a way of allowing an end-user to modify enumeration values once application is released?

I am just starting out with CodeFluent and beginning to really like it. My question is: I set a property of an entity to enumeration. How can I allow an end-user to add extra values (that are stored afterwards as additional choices) to an enumeration? Or should I use another entity to store those values/choices instead?
For instance: let's say I have a product and a producttype. My producttype is an enumeration (frozen, fresh, seasonal), and down the road, the user wants additional types (i.e.: organic, stationary). Should those be enumeration values or a separate entity?
If a separate entity.....I'm not really sure how I define the relationship (1 to 1, 1 to many - i.e. 1 producttype can have many products)?
You can't add values to an enum at runtime, that's impossible in .NET, so it's also impossible with CodeFluent.
So, you want to create another entity that will store the list of enums. That would be a 1:M relation. This is how you would layout that relation:
Each enumeration value would be a row in the ProductType table. With CodeFluent, you can declare "instances" for an entity that will become rows in the final table, so here, you can declare your initial enum values using instance, so use the instance grid on the ProductType entity, and add instances:
Note in this case, maybe you want to create the ProductType's Id property as an int without identity (if you don't want those enum int values generated by the database).

Best practice : How to retrieve all EntityIds based on some condition applied on the state?

Here is my use case:
case class Organization(id: String = UUID.randomUUID().toString, userId: String)
case class OrganizationState(organization: Option[Organization])
case CreateOrganization extends OrganizationCommand
case OrganizationCreated extends OrganizationEvent
class OrganizationEntity extends PersistentEntity[OrganizationCommand, OrganizationEvent, OrganizationState]
POST /organizations?userId=1 <= creates an organization associated with user 1
GET /organizations?userId=1 <= retrieves all organizations associated with user 1
How can I implement my service in order to insure consistency ?
I try using a CassandraReadSide to maintain a table mapping userId with organizationId but this table is eventually consistent.
Do I need to create another Entity with the userId as entityId ?
In fun-cqrs, there is the Projection.onEvent that allows to know when an event was processed by a projection.
See https://groups.google.com/forum/#!topic/lagom-framework/JG71x5W5h7I
Readside is the answer as you point out. It is of course eventually consistent. Alternatively you can create another entity and have one entity directly invoke the other but it will still be eventually consistent from the perspective of the client.
The question you have to ask yourself is why the POST and GET have to be immediately consistent? There are ways of accomplishing this but the trade offs you make would usually impact performance and may not align with lagom.

Eloquent Friendly Column Name

We're currently transitioning from one database to another. A table in our legacy database has column names that are less than ideal, for example:
some_crazy_name__xyz
In our new database, we'd like to have a column name like:
someCrazyName
In the short term, we have to work with data from our legacy database. At some point in the near future, we'd like to switch over without having to refactor all of our Eloquent code to query for different column names. For example:
$model = MyModel::where('someCrazyName', '=', 1);
I'm currently extending the Model class, where all implementing models provide a map of terrible names to friendly names:
class MyModel extends BaseModel {
$columnMap = array(
'someCrazyName' => 'some_crazy_name__xyz'
);
}
This works well where I can use __get and __set in BaseModel to lookup properties in my map, for example:
$myModel = new MyModel;
// ...
echo $myModel->someCrazyName;
However, this obviously doesn't work well with queries without having to always use my map to look up column names. I'm wondering if it's possible without having to override all of the methods within Illuminate\Database\Eloquent\Model, Illuminate\Database\Query\Builder and Illuminate\Database\Eloquent\Builder that deal with columns, where the underlying query that is built always maps to the correct column? Then after we transition databases, we can remove that one piece of code rather then remove potentially thousands of column name mappings.
This is what you need: https://github.com/jarektkaczyk/eloquence/wiki/Mappable
It's not only for mapping badly_named_columns to something_useful, but also can be used for relational mappings:
// simple aliasing
User::where('cool_name', 'value') // where badName = ?
// relations, eg. User hasOne Profile
User::where('first_name', 'Jon') // search through related profiles table
// and obviously mutators:
$user->first_name == $user->profile->first_name
$user->cool_name = 'Jon' // becomes $user->badName = 'value'
$user->cool_name; // 'Jon'
One way to do it would be with accessors.
For example, in MyModel you could define an accessor for the some_crazy_name__xyz column like this:
public function getSomeCrazyNameAttribute()
{
return $this->attributes['some_crazy_name__xyz'];
}
You can then transparently refer to that column with $mymodel->someCrazyName. You can also define a mutator to set the value.
Admittedly, this may not be the best solution if you have MANY values like this. But it does have one important benefit: later on, if you refactor your database so that the column some_crazy_name__xyz is actually called someCrazyName, all you need to do is remove that function from your model. And, to my mind at least, it's simpler than trying to override a bunch of methods on the various classes involved.
And unfortunately, it doesn't adequately address the use of column names in queries. For that, you might want to look at the repository pattern. But in any event, it looks like there's going to be a lot of coding involved.
Finally, you haven't mentioned what database you're using. If it's MySQL, it is possible to create updatable and insertable views. Using a view, you could simply map old column names to new, and point your Eloquent model at the view instead of a table. Other database servers may provide similar functionality.

possible to return only one column using JPA

I have an Open JPA entity and it successfully connects a many-to-many relationship. Right now I successfully get the entire table, but I really only want the ID's from that tables. I plan on calling the database later to reconstruct the entities that I need (according to the flow of my program).
I need only the ID's (or one column from that table).
1) Should I try and restrict this in my entity beans, or in the stateless session beans that I will be using to call the entity beans
2) If I try and do this using JPA, how can I specify that I only get back the ID's from the table, instead of the whole table? So far looking online, I don't see a way that you can do this. So I am guessing there is no way to do this.
3) If I simply just manipulate the return values, should I create a separate class that I will be returning to the user that will return only the required id list to the user?
I could be completely wrong here, but from the looks of it, I don't think there is a simple way to do this using JPA and I will have to return a custom object instead of the entity bean to the user (this custom object would only hold the id's as opposed to the whole table as it currently does)
Any thoughts... I don't think this is really relevant, but people are always asking for code, so here you go...
#ManyToMany(fetch=FetchType.EAGER)
#JoinTable(name="QUICK_LAUNCH_DISTLIST",
joinColumns=#JoinColumn(name="QUICK_LAUNCH_ID"),
inverseJoinColumns=#JoinColumn(name="LIST_ID"))
private List<DistributionList> distributionlistList;
Currently how I get the entire collection of records. Remember I only want the id...
try
{
//int daSize = 0;
//System.out.println("Testing 1.2..3...! ");
qlList = emf.createNamedQuery("getQuickLaunch").getResultList();
}
This is how I call the Entity beans. I am thinking this is where I will have to programatically go through and create a custom object similar to the entity bean (but it just has the ID's and not the whole table, and attempt to put the id's in there somewhere.
What are your thoughts?
Thanks
I believe I just figured out the best solution to this problem.
This link would be the answer:
my other stack overflow answer post
But for the sake of those too lazy to click on the link I essentially used the #ElementCollection attribute...
#ElementCollection(fetch=FetchType.EAGER)
#CollectionTable(name="QUICK_LAUNCH_DISTLIST",joinColumns=#JoinColumn(name="QUICK_LAUNCH_ID"))
#Column(name="LIST_ID")
private List<Long> distListIDs;
That did it.
Sounds like you want something like this in your quickLaunch class:
#Transient
public List<Integer> getDistributionListIds () {
List<Integer> distributionListIds = new LinkedList<Integer>();
List<DistributionList> distributionlistList = getDistributionlistList();
if (distributionlistList != null) {
for (DistributionList distributionList : distributionlistList)
distributionListIds.add(distributionList.getId());
}
return distributionListIds;
}
I had to guess a little at the names of your getters/setters and the type of DistributionList's ID. But basically, JPA is already nicely handling all of the relationships for you, so just take the values you want from the related objects.

Sort order in Core Data with a multi-multi relationship

Say I'm modeling a school, so I have 2 Entities: Student and Class. For whatever reason, I want each class roster to have a custom sort order. In a simple relationship, this would mean giving Student a sortOrder attribute and just sorting the list by this number. Issue is, a Student might be order 3 in one Class and order 6 in another. How would I store these orderings in Core Data in a way that I can easily access them and sort my lists properly?
Student Class
classes <<--------->> students
^ ^
| |
unordered ordered
This diagram might help explain what I'm trying to do. The students "roster" I would want to be fetched in a specific order stored somewhere, which could be any ordering. Storing this ordering is what I'm not sure how to do in a way that's the most efficient. Creating a bunch of Order objects and trying to manage the links sounds like a lot of overhead, and it feels like there must be a better way.
If the ordering of students can be described by one or more NSSortDescriptors, you could create a fetched property on the Class entity that fetches the students and applies the sort descriptor. Alternatively, it may be easier (depending on your use case) to apply the sort descriptor(s) to the NSFetchedResultsController that you're using to deal with the class' students collection.
If you can't use an NSSortDescriptor, then you'll need an index attribute (or name of your choice) on the Student entity if there's only one ordering or a collection of Order entities describing the index in each ordering for each Student. You'll be responsible for maintaing these index values. Unfortunately, there's no easy way to do this in Core Data. It's just a lot of work.
Student <<->> StudentClass <<->> Class
StudentClass
----
studentID
order
classID
Then you can select as necessary.
For example, you have a student. Fetch all StudentClass where StudentID is student.studentID. You then have the order, as well as access to the Class.
You'll likely want to add some business logic to make your life easier. Also, if you're not already using it, take a peek at MOGenerator: https://github.com/rentzsch/mogenerator
EDIT: I'd really like to know why this is getting voted down. Comments would be much appreciated.