since four days I'm trying to figure out how to follow a reference from one to another class, starting from the class which is beeing referenced. In SQL-Django there is a related_name to achieve this...
For example I have this class:
class MyClass(Document):
...
other_classes = ListField(ReferenceField(Other_Class))
and this one:
class Other_Class(Document):
...
Now I want to go from Other_Class to MyClass... Any ideas?
Thanks,
Ron
Here is a test case showing how to query it:
import unittest
from mongoengine import *
class StackOverFlowTest(unittest.TestCase):
def setUp(self):
conn = connect(db='mongoenginetest')
def test_one_two_many(self):
class MyClass(Document):
other_classes = ListField(ReferenceField("OtherClass"))
class OtherClass(Document):
text = StringField()
MyClass.drop_collection()
OtherClass.drop_collection()
o1 = OtherClass(text='one').save()
o2 = OtherClass(text='two').save()
m = MyClass(other_classes=[o1, o2]).save()
# Lookup MyClass that has o1 in its other_classes
self.assertEqual(m, MyClass.objects.get(other_classes=o1))
# Lookup MyClass where either o1 or o2 matches
self.assertEqual(m, MyClass.objects.get(other_classes__in=[o1, o2]))
The main question is do you need to store a list of references in the MyClass? It might be more efficient to store the relationship just on OtherClass..
Try this query:
oc = Other_Class()
MyClass.objects.find( other_classes__all = [oc.id] )
While thinking about my problem I came up with a solution.
I just add the ID of my referenced class to my model.
Here's an example:
class MyClass(Document):
...
other_classes = ListField(ReferenceField(Other_Class))
class Other_Class(Document):
myclass = ReferenceField(MyClass)
I'm not quite sure if this is the Mongo-way to do it but I'm pretty sure it works :)
Optionally you can omit the other_classes attribute in MyClass to avoid redundancy but then you need a query like this to get the "child" objects:
Other_Class.objects(myclass = myclass.id)
Related
Assume, we have model
class BaseModel(models.Model):
is_a = models.BooleanField()
and two models related to this one:
class A(models.Model):
value_1 = models.IntegerField()
base = models.ForeignKey(BaseModel, related_name='a')
class B(models.Model):
value_1 = models.IntegerField()
value_2 = models.IntegerField()
base = models.ForeignKey(BaseModel, related_name='b')
What I need is to refer to A or B depending on is_a property.
For example,
base = BaseModel.objects.get(id=1)
if base.is_a:
obj = A.objects.create(value_1=1, base=base)
else:
obj = B.objects.create(value_1=1, value_2=2, base=base)
return obj
or
if base.is_a:
queryset = base.a.all()
else:
queryset = base.b.all()
return queryset
i.e., every time I have to check the is_a property.
Is there more graceful way?
There are two only related models, A and B, no other ones will appear in the nearest future.
Part of the problem can be solved with django-polymorphic, e.g.:
class A(PolymorphicModel):
...
class B(A):
...
This allows to retrieve all A's and B's with one request like base.b.all(), but the problem here is that every B creates instance of A, which is unwanted.
I've considered GenericForeignKey as well. As far as I understood it has a number of limitations like "1) You can't use GenericForeignKey in query filters ; 2) a GenericForeignKey won't appear in a ModelForm" (from GenericForeignKey or ForeignKey).
One idea is to add choices to the BaseModel to have a string representation of your boolean value. If you set the strings equal to the A and B model names, you can use the model.get_foo_display() method to return the name of the model. Then use the Python getattr() method to access attributes as variables.
class BaseModel(models.Model):
base_model_choices = (
(True, 'A'),
(False, 'B'),
)
is_a = models.BooleanField(choices=base_model_choices)
For example,
base = BaseModel.objects.get(id=1)
queryset = base.getattr(models, get_is_a_display()).all()
obj = getattr(models, get_is_a_display()).objects.create(base=base)
Could someone translate this Java Pseudo code with generics to Django models? I don't understand the content type concept. It would also be possible to leave out the map and just have a list of KeyValuePairs or KeyValueExamples.
class Dictionary<T extends KeyValuePair>
class KeyValuePair
String key
String value
class KeyValueExample extends KeyValuePair
String example
class Container
Dictionary<KeyValuePair> itemsOne
Dictionary<KeyValueExample> itemsTwo
Django's contenttypes doesn't have anything common with generics from Java. Python has a dynamic type system so there is no need for generics.
This means that you can put any object of any class into the dictionary:
class Container(object):
def __init__(self):
self.itemsOne = {}
self.itemsTwo = {}
container = Container()
container.itemsOne['123'] = '123'
container.itemsOne[321] = 321
container.itemsTwo[(1,2,3)] = "tuple can be a key"
If you want to implement your classes in django models then code could be something like this:
class KeyValuePairBase(models.Model):
key = models.CharField(max_length=30)
value = models.CharField(max_length=30)
class Meta:
abstract = True
class KeyValuePair(KeyValuePairBase):
pass
class KeyValueExample(KeyValuePairBase):
example = models.CharField(max_length=30)
class Container(models.Model):
items_one = models.ManyToManyField(KeyValuePair)
items_two = models.ManyToManyField(KeyValueExample)
# usage of these models
kvp = KeyValuePair.objects.create(key='key', value='value')
kve = KeyValueExample.objects.create(key='key', value='value',
example='Example text')
container = Container.objects.create()
container.items_one.add(kvp)
container.items_two.add(kve)
I am trying to use google's ndb model, adding some auto fields and definitions prior to model definition. The below code works well. My question is, though, any specific ndb model implementation is not used ( given I will be destroyed, if google changes anything) do you see any issue with portability of below
class MetaModel(type):
def __new__(cls,name,bases,attrs):
super_new = super(MetaModel,cls).__new__
if name == "Model":
return super_new(cls,name,bases,attrs)
if attrs.get('auto_date_time',True):
attrs['date_add'] = ndb.DateTimeProperty(auto_now_add= True)
attrs['date_upd'] = ndb.DateTimeProperty(auto_now= True)
attrs['_get_kind'] = classmethod(get_kind)
attrs['__name__'] = name
attr_meta = attrs.get('Meta',None)
if attr_meta is None:
meta = type('meta',(object,),dict())
else:
meta = attr_meta
kwargs= {}
model_module = sys.modules[attrs['__module__']]
kwargs['app_label'] = model_module.__name__.split('.')[-2]
_meta = Options(meta,name,**kwargs)
attrs['_meta'] = _meta
return type(name,(ndb.Model,),attrs)
class Model(object):
__metaclass__ = MetaModel
class TesTModel(Model):
name = ndb.StringProperty(indexed=False)
tm = TestModel(name='This is the test model')
tm.put()
This seems pretty fragile. Sounds like an expando model might work for you?
Edit (based on clarification below): metaclasses and type really should be a last resort. They're confusing and hard to get right. For example, in your code snippet, subclasses of Model get ndb's metaclass instead of the one above:
class T1(Model):
pass
>>> T1().to_dict()
T1 {'date_upd': None, 'date_add': None}
class T2(Model):
auto_date_time = False
class T3(T2):
auto_date_time = True
>>> T2.__metaclass__
<class 'ndb.model.MetaModel'>
>>> T3().to_dict()
{}
You can avoid some craziness by deriving your metaclass from ndb.MetaModel:
class MyMetaModel(ndb.MetaModel):
def __new__(cls, name, bases, attrs):
return super(MyMetaModel,cls).__new__(cls, name, bases, attrs)
class MyModel(ndb.Model):
__metaclass__ = MyMetaModel
class AutoTimeModel(MyModel):
date_add = ndb.DateTimeProperty(auto_now_add=True)
date_upd = ndb.DateTimeProperty(auto_now=True)
I have two models:
class ModelOne(models.Model):
something = models.TextField[...]
class ModelTwo(models.Model):
other_something = models.TextField[...]
ref = models.ForeignKey(ModelOne)
And I want to write function in ModelOne which return me all related objects from ModelTwo.
It's important: In ModelOne.
How to do it?
Invoke self.modeltwo_set.all().
Is it possible to instantiate a subclassed model from its parent?
class Object1(models.Model):
field1a = models.CharField()
field1b = models.CharField()
feild1c = models.ForeignKey(Object4)
class Object2(Object1):
field3 = models.CharField()
class Object3(Object1):
field3 = models.CharField()
class Object4(models.Model):
field4 = models.CharField()
What I want to do is create the base class first and then based on some rule instantiate one of the subclasses but using the already created base class.
Something like:
obj4 = Object4(field4='d')
obj1 = Object1(field1a='a', field1b='b', field1c=obj4)
if somerule:
obj2 = Object2(object1_ptr=obj1, field2='2')
else:
obj3 = Object3(object1_ptr=obj1, field3='3')
I don't want to repeat the Object1 fields in the if/else clauses. Is it possible to accomplish this? When I try this I get a Foreign key error;
Cannot add or update a child row: A foreign key constraint fails
I recommend doing something like this:
attr = dict(field1a='a', field1b='b', field1c=obj4)
obj1 = Object1(**attr)
if somerule:
attr["field2"] = 2
obj2 = Object2(**attr)
else:
attr["field3"]='3'
obj3 = Object3(**attr)
Be aware that the dictionary attr changes in place.
What you're doing is almost correct, but if you want to copy it you will have to remove the primary key.
So... this should fix it: del obj2.id
Do note however that if some other model references your model with a foreign key that it references obj1, not obj2. And obj1 will, ofcourse, still exist.