Performing multiple queries on Many to Many Field Django - django-models

My main models look like this,
class BusStation(models.Model):
name = models.CharField()
location = models.CharField()
class Bus(models.Model):
name = models.CharField()
routes = models.ManyToManyField(BusStation)
If a user intends to board a bus, they would need to include take_off_station and destination_station within their search query. The problem is, I'm trying to get the list of buses that contain both take_off and destination points within their route.
I tried:
Bus.objects.filter(
Q(routes__name__icontains=take_off_station) &
Q(routes__name__icontains=destination_station))
this doesn't return anything. When I replaced & for | it returns a queryset that contains at least one of the results i needed. So Please, How do I return all buses that contain both, take_off and Destination within their routes

Related

ndb.KeyProperty value get() returns None

I'm storing the key to another entity in an ndb.KeyPropery attribute called teacher
class Section(ndb.Model):
name = ndb.StringProperty(required=True)
teacher = ndb.KeyProperty(required=True, kind=Staff)
students = ndb.IntegerProperty(repeated=True)
active = ndb.BooleanProperty(default=True)
I'm storing things there just fine, but when I retrieve a value it doesn't seem to fully behave like an ndb.Key
(in interactive console on dev server...)
from google.appengine.ext import ndb
import amt
from sections.model import Section
section = Section.query(Section.name == 'test').fetch()[0]
print(section.teacher)
print(type(section.teacher))
print(section.teacher.kind())
print(section.teacher.id())
print(section.teacher.get())
print(ndb.Key(section.teacher.kind(), int(section.teacher.id())).get())
gives...
Key('Staff', '5486563022602240')
<class 'google.appengine.ext.ndb.key.Key'>
Staff
5486563022602240
None
Kxxxxxxx, Mxxx
So why does section.teacher.get() return None and ndb.Key(section.teacher.kind(), int(section.teacher.id())).get() return my entity (__str__ is overridden to just print out a name...)
Notice the difference in the key Key('Staff', '5486563022602240') and your code that fetches ndb.Key(section.teacher.kind(), int(section.teacher.id()) these are different keys.
The first has a key_name defined (str) and your fetching successfully with an id (int).
Maybe you stored the wrong key in teacher the first time around.
How did you construct your original key ?

LDAPMAP - Mapping SAP data to LDAP via RSLDAPSYNC_USER function

We are looking at syncing some of our LDAP (Active Directory) data with what is stored in SAP. SAP provides several function modules that allow you to write a custom program to handle mapping the data, but we are looking to use the provided solution that makes use of RSLDAPSYNC_USER.
The issue I'm having is understanding how the mapping of fields is performed in LDAPMAP. In particular, when performing the Mapping Overview, where are the structures as shown below defined?
Also, we have a function module that is currently available for grabbing all of the fields we would like to send to LDAP, but can the screen shown below be used to call a custom function module to grab the data I require? If so, then please give an example.
Thanks,
Mike
I am not sure if that is what you ask. As an answer to your second question:
You can give attributes that you want to get. The LDAP_READ function will return the results in entries parameter.
CALL FUNCTION 'LDAP_READ'
EXPORTING
base = base
* scope = 2
filter = filter
* attributes = attributes_ldap
timeout = s_timeout
attributes = t_attributes_ldap
IMPORTING
entries = t_entries_ldap "<< entries will come
EXCEPTIONS
no_authoriz = 1
conn_outdate = 2
ldap_failure = 3
not_alive = 4
other_error = 5
OTHERS = 6.
Entries parameter looks like:
Attributes parameter looks like:

change a db from a certain point in time, when the change doesn't fit the already existing data

I have a model that looks like this:
class Report(models.Model):
updater = models.CharField(max_length=15)
pub_date = models.DateTimeField(auto_add_now=True)
identifier = models.CharField(max_length=100)
... and so on...
There are some more fields but they are irrelevant to the question. Now the site has very simple functions - the users can see older reports and their data, and can edit them or add new ones.
However, the identifier field is actually an integer that symbolizes a log file that is being reported. Most of the times, each report has one log. But sometimes it has more than one. I did it as a CharField because I built the site to replace an older sharepoint 2003 website, where that field was treated as simple text. So I want that in my next version, it would be like it should be, i.e. like this:
class Report(models.Model):
updater = models.CharField(max_length=15)
pub_date = models.DateTimeField(auto_add_now=True)
... and so on...
class Log(models.Model):
report = models.ForeignKey(Report)
identifier = models.IntegerField()
The problem is, since in the old site that field was a CharField, people used this as they liked. Meaning, even if they updated various logs in the same report they just did it like this <logid1>, <logid2>. Sometimes they added some text <logid1> which is related to <logid2>.
So I want to change this, but I don't want to lose all the old data, and I can't fix all those edge cases (the DB contains around 22 thousand reports). I thought about adding this to report:
def disp_id(self):
if self.pub_date < ... #the day I'll do the update
return self.identifier
else:
return ', '.join([log.identifier for log in self.log_set.all()])
But then I'm not really getting rid of the old field now am I? I'm just adding a new one and keeping the original null from a certain date.
As far as I know, what I want to do is impossible. I'm only asking because I know that maybe I'm not the first one to deal with this sort of thing and maybe there is a solution that I'm not aware of.
Hope my explanation is clear enough, thanks in advance!
class Report(models.Model):
updater = models.CharField(max_length=15)
pub_date = models.DateTimeField(auto_add_now=True)
identifier = models.CharField(null=True)
... and so on...
logs = models.ManyToManyField(Log,null=True)
class Log(models.Model):
identifier = models.IntegerField()
Make the above model , and then make a script as follow:
ident_list = []
for reports in Report.objects.all():
identifiers = reports.identifiers.split(',')
for idents in identifiers:
if not idents in ident_list:
log = Log.create(**{'identifier' : int(idents)})
ident_list.append(int(idents))
else:
log = Log.objects.get(identifier = int(idents))
report.log.add(log)
Check the data before removing the column identifiers from the table Report.
Does it solves your purpose now ?

What is the best practice way to initialize an actor from the database

I have a top level actor (under the guardian), called Groups which on startup needs to load the list of groups from the database and create a bunch of child actors based on those groups in the database.
I have placed the database load code inside of the preStart function as I don't want any messages to be processed before the groups are loaded.
Currently my Groups actor looks like this;
var groups: Map[String, ActorRef] = Map()
override def preStart() = {
groups = getGroupsFromDB() map createGroup
}
def createGroup(pair: (String, Long)) = {
val (name, id) = pair
val group = context.actorOf(Props(new Group(id, name)), name = name)
name -> group
}
However I don't believe this is the best way to handle this, as what happens if the database server is not available? So what is the best pratice way of handling data initialization from a database?
The Akka documentation explains how to supervise top level actors for fault-tolerance.
You can apply the principles there to manage the exceptions you may find if the DB is not available.

Python - read with key in App Engine

I have a python program in Google App Engine
When finding an object in the datastore when I have the key as a string, how can I do a direct read. Below is my code which is performing a loop, not good.....
class Opportunity(db.Model):
customer = db.ReferenceProperty(Customer,collection_name='opportunitys')
BNusername = db.StringProperty()
opportunity_no = db.StringProperty()
# etc etc etc.....
#BnPresets holds the object key as a string
opportunitys = Opportunity.all()
opportunitys.filter('BNusername =',BnPresets.myusername)
for oprec in opportunitys:
if str(oprec.key()) == BnPresets.recordkey:
opportunity = oprec
# I have the object here and can process etc etc
You can instantiate db.Key from string by passing it directly to the constructor:
opportunity_key = db.Key(BnPresets.recordkey)
Once you have that, simply db.get to obtain the entity identified by this key:
opportunity = db.get(opportunity_key)
I guess (by looking at the query you use) that you also want to verify the username of the object you got:
if opportunity.BNusername == BnPresets.myusername
process_opportunity(opportunity)
That should be pretty much it. The bottom line is that you should use the key first - as it uniquely identifies your entity - rather than querying for some other property and iterating through results.

Resources