I think the best way to ask this question is with some code... can I do this:
class MyModel(models.Model):
foo = models.CharField(max_length = 20)
bar = models.CharField(max_length = 20)
def get_foo(self):
if self.bar:
return self.bar
else:
return self.foo
def set_foo(self, input):
self.foo = input
foo = property(get_foo, set_foo)
or do I have to do it like this:
class MyModel(models.Model):
_foo = models.CharField(max_length = 20, db_column='foo')
bar = models.CharField(max_length = 20)
def get_foo(self):
if self.bar:
return self.bar
else:
return self._foo
def set_foo(self, input):
self._foo = input
foo = property(get_foo, set_foo)
note: you can keep the column name as 'foo' in the database by passing a db_column to the model field. This is very helpful when you are working on an existing system and you don't want to have to do db migrations for no reason
A model field is already property, so I would say you have to do it the second way to avoid a name clash.
When you define foo = property(..) it actually overrides the foo = models.. line, so that field will no longer be accessible.
You will need to use a different name for the property and the field. In fact, if you do it the way you have it in example #1 you will get an infinite loop when you try and access the property as it now tries to return itself.
EDIT: Perhaps you should also consider not using _foo as a field name, but rather foo, and then define another name for your property because properties cannot be used in QuerySet, so you'll need to use the actual field names when you do a filter for example.
As mentioned, a correct alternative to implementing your own django.db.models.Field class, one should use the db_column argument and a custom (or hidden) class attribute. I am just rewriting the code in the edit by #Jiaaro following more strict conventions for OOP in python (e.g. if _foo should be actually hidden):
class MyModel(models.Model):
__foo = models.CharField(max_length = 20, db_column='foo')
bar = models.CharField(max_length = 20)
#property
def foo(self):
if self.bar:
return self.bar
else:
return self.__foo
#foo.setter
def foo(self, value):
self.__foo = value
__foo will be resolved into _MyModel__foo (as seen by dir(..)) thus hidden (private). Note that this form also permits using of #property decorator which would be ultimately a nicer way to write readable code.
Again, django will create _MyModel table with two fields foo and bar.
The previous solutions suffer because #property causes problems in admin, and .filter(_foo).
A better solution would be to override setattr except that this can cause problems initializing the ORM object from the DB. However, there is a trick to get around this, and it's universal.
class MyModel(models.Model):
foo = models.CharField(max_length = 20)
bar = models.CharField(max_length = 20)
def __setattr__(self, attrname, val):
setter_func = 'setter_' + attrname
if attrname in self.__dict__ and callable(getattr(self, setter_func, None)):
super(MyModel, self).__setattr__(attrname, getattr(self, setter_func)(val))
else:
super(MyModel, self).__setattr__(attrname, val)
def setter_foo(self, val):
return val.upper()
The secret is 'attrname in self.__dict__'. When the model initializes either from new or hydrated from the __dict__!
It depends whether your property is a means-to-an-end or an end in itself.
If you want this kind of "override" (or "fallback") behavior when filtering querysets (without first having to evaluate them), I don't think properties can do the trick. As far as I know, Python properties do not work at the database level, so they cannot be used in queryset filters. Note that you can use _foo in the filter (instead of foo), as it represents an actual table column, but then the override logic from your get_foo() won't apply.
However, if your use-case allows it, the Coalesce() class from django.db.models.functions (docs) might help.
Coalesce() ... Accepts a list of at least two field names or
expressions and returns the first non-null value (note that an empty
string is not considered a null value). ...
This implies that you can specify bar as an override for foo using Coalesce('bar','foo'). This returns bar, unless bar is null, in which case it returns foo. Same as your get_foo() (except it doesn't work for empty strings), but on the database level.
The question that remains is how to implement this.
If you don't use it in a lot of places, simply annotating the queryset may be easiest. Using your example, without the property stuff:
class MyModel(models.Model):
foo = models.CharField(max_length = 20)
bar = models.CharField(max_length = 20)
Then make your query like this:
from django.db.models.functions import Coalesce
queryset = MyModel.objects.annotate(bar_otherwise_foo=Coalesce('bar', 'foo'))
Now the items in your queryset have the magic attribute bar_otherwise_foo, which can be filtered on, e.g. queryset.filter(bar_otherwise_foo='what I want'), or it can be used directly on an instance, e.g. print(queryset.all()[0].bar_otherwise_foo)
The resulting SQL query from queryset.query shows that Coalesce() indeed works at the database level:
SELECT "myapp_mymodel"."id", "myapp_mymodel"."foo", "myapp_mymodel"."bar",
COALESCE("myapp_mymodel"."bar", "myapp_mymodel"."foo") AS "bar_otherwise_foo"
FROM "myapp_mymodel"
Note: you could also call your model field _foo then foo=Coalesce('bar', '_foo'), etc. It would be tempting to use foo=Coalesce('bar', 'foo'), but that raises a ValueError: The annotation 'foo' conflicts with a field on the model.
There must be several ways to create a DRY implementation, for example writing a custom lookup, or a custom(ized) Manager.
A custom manager is easily implemented as follows (see example in docs):
class MyModelManager(models.Manager):
""" standard manager with customized initial queryset """
def get_queryset(self):
return super(MyModelManager, self).get_queryset().annotate(
bar_otherwise_foo=Coalesce('bar', 'foo'))
class MyModel(models.Model):
objects = MyModelManager()
foo = models.CharField(max_length = 20)
bar = models.CharField(max_length = 20)
Now every queryset for MyModel will automatically have the bar_otherwise_foo annotation, which can be used as described above.
Note, however, that e.g. updating bar on an instance will not update the annotation, because that was made on the queryset. The queryset will need to be re-evaluated first, e.g. by getting the updated instance from the queryset.
Perhaps a combination of a custom manager with annotation and a Python property could be used to get the best of both worlds (example at CodeReview).
Related
models.py:
class office_list(models.Model):
name = models.CharField(max_length= 100)
num_of_pax = models.IntegerField()
class tg_list(models.Model):
name = models.CharField(max_length= 100)
num_of_pax = models.IntegerField()
How can I check that the office_list name equals to the tg_list name?
I want to check if any of the office_list.name == any of the tg_list.name
if you want
any of the office_list.name == any of the tg_list.name
you can do simple query with exists:
names = tg_list.objects.values_list('name', flat=True)
office_list.objects.filter(name__in=names).exists()
From the Django doc :
To compare two model instances, just use the standard Python comparison operator, the double equals sign: ==. Behind the scenes, that compares the primary key values of two models.
or :
Youu can do with __eq__ in python too:
See python docs too.
The accepted answer requires an DB call, and specifically checks 1 field. In a more realistic scenario, you would be checking some subset of fields to be equal - likely ignoring PK's, creation timestamps, amongst other things.
A more robust solution would be something like:
class MyModel(Model):
some_field_that_is_irrelevant_to_equivalence = models.CharField()
some_char_field = models.CharField()
some_integer_field = models.IntegerField()
_equivalent_if_fields_equal = (
'some_char_field',
'some_integer_field',
)
def is_equivalent(self, other: 'MyModel') -> bool:
"""Returns True if the provided `other` instance of MyModel
is effectively equivalent to self.
Keyword Arguments:
-- other: The other MyModel to compare this self to
"""
for field in self._equivalent_if_fields_equal:
try:
if getattr(self, field) != getattr(other, field):
return False
except AttributeError:
raise AttributeError(f"All fields should be present on both instances. `{field}` is missing.")
return True
Suppose I have the following structure:
class Foo(models.Model):
pass
class Bar(models.Model):
foo = models.ForeignKey(Foo, related_name='bars')
I want the individual Bar objects to be keyed on both an auto-incrementing ID and the parent Foo object. For each Foo I want the Bars underneath to always be id'd 1,2,3. The ultimate aim is to access Bars via URIs such as:
/foos/1/bars/1
/foos/2/bars/1
Notice that there are two Bars with the same ID, but the primary key comes from the uniqueness of the id's of both the Bar and its parent Foo.
I thought I'd found my answer in the unique_together attribute of the Meta class:
class Bar(models.Model):
foo = models.ForeignKey(Foo, related_name='bars')
class Meta:
unique_together = ('foo', 'id')
But unfortunately this still results in a unique ID for each Bar. I always want the first Bar for each Foo to have an ID of 1.
You can't do that with the ID, because that's allocated by the database and is always unique across the whole table. If you really want this, you will have to define a separate field and increase it each time you create a bar for your foo.
A naive implementation might be something like:
class Bar(models.Model):
foo_order = models.IntegerField()
foo = models.ForeignKey(Foo, related_name='bars')
class Meta:
unique_together = ('foo', 'foo_order')
def save(self, *args, **kwargs):
if not self.foo_order:
self.foo_order = self.bar_set.count() + 1
super(Bar, self).save(*args, **kwargs)
(Note that this is probably subject to all sorts of race conditions, so be careful.)
Now you can use the field combination in your view to get the relevant Bar:
def bar_view(request, foo_id, order):
my_bar = Bar.objects.get(foo_id=foo_id, foo_order=order)
As a side note, I don't actually need to store this identifier on any object. Rather than
/foos/1/bars/1
resulting in a lookup for a Bar with pk set to 1, I can just take the request and return something like
Foo.objects.get(id=1).bars.all()[0]
I.e. thereby mapping to the first Bar. so
/foos/n/bars/m
maps to the mth Bar under the Foo with primary key n.
Daniel's solution actually answers my original question, so I'm accepting that as the answer.
How does Django translate this <bound method Child.parent_identity of <Child: >> object in a string object, and displays it as such in my django-admin "inline" Child class idparent field ?
What does Django do ?
I have the following application structure:
##========================models.py
...
from django_extensions.db.fields import UUIDField
class Parent(models.Model):
id = UUIDField(primary_key=True)
class Child(models.Model):
parent = models.ForeignKey(Parent)
idparent = models.CharField(max_length=100)
def parent_identity(self):
return self.parent_id
#========================admin.py
class ChildForm(forms.ModelForm):
class Meta:
model = Child
exclude = []
def __init__(self, *args, **kwargs):
super(ChildForm, self).__init__(*args, **kwargs)
#print self.instance.parent_identity
self.initial['idparent'] = self.instance.parent_identity
class ChildInline(admin.TabularInline):
model = Child
extra = 1
form = ChildForm
class ParentAdmin(admin.ModelAdmin):
exclude = []
inlines = [ChildInline]
#list_display, etc
admin.site.register(Parent,ParentAdmin)
My inline idparent field displays the Parent id field CORRECTLY in the admin inline interface. Being a newbie, it's magic for me, because self.instance.parent_identity is initially not a string object.
print self.instance.parent_identity
#it prints : <bound method Child.parent_identity of <Child: >>
But how to explictly print the string content as follows
>>print self.instance.parent_identity
#would print : fffeee29-7ac6-42eb-8a8d-eb212d2365ff
That is, how to get it so as to deal with it in the ChildForm class ?
UPDATE
I do not mind specifically about "UUID in the form when the instance hasn't been created yet"
and i do not want to provide an initial value myself.
I want my still empty (extra) Child fields (one field in my example code: idparent) to contain by default something which is Parent variable.
Is it possible ?
Django templates automatically call any object that is callable; e.g. the callable() function returns True when you pass the object in. From the Variables section in the template documentation:
If the resulting value is callable, it is called with no arguments. The result of the call becomes the template value.
Bound methods are callable, so instead of using self.instance.parent_identity, the template uses the output of self.instance.parent_identity().
In your own code, you generally already know that something is a method and you call it explicitly:
def __init__(self, *args, **kwargs):
super(ChildForm, self).__init__(*args, **kwargs)
self.initial['idparent'] = self.instance.parent_identity()
You can treat the parent_identity method as an attribute; have Python call it automatically without you having to call it explicitly. If you never have to pass in an argument, then that might make sense. You do this by decorating the method with the #property decorator:
class Child(models.Model):
parent = models.ForeignKey(Parent)
idparent = models.CharField(max_length=100)
#property
def parent_identity(self):
return self.parent_id
at which point self.instance.parent_identity will give you the return value of that method.
Take into account that the UUIDField only is given a value on pre-save; it'll be None until the object is saved in a database.
If you really wanted to UUID in the form when the instance hasn't been created yet, you'll have to provide an initial value yourself:
import uuid
class ParentAdmin(admin.ModelAdmin):
exclude = []
inlines = [ChildInline]
def __init__(self, *args, **kwargs):
super(ParentAdmin, self).__init__(*args, **kwargs)
self.fields['id'].initial = uuid.uuid4
You are calling a function, which means you need to use it as such:
self.initial['idparent'] = self.instance.parent_identity()
Alternately you could wrap it with the #property decorator and continue using it as you are, notice that you need to use self.parent.id if you want to access the parent's id:
class Child(models.Model):
parent = models.ForeignKey(Parent)
idparent = models.CharField(max_length=100)
#property
def parent_identity(self):
return self.parent.id
Consider this Django schema:
class Foo(models.Model):
# ...
class FooOption(models.Model):
foo = models.ForeignKey(foo, related_name='options')
key = models.CharField(max_length=64)
value = models.TextField()
class Meta:
unique_together = [('foo', 'key')]
Essentially, FooOptions works a key-value set for each Foo.
<edit>
There's a known set of keys that the system uses,
Every Foo has a number of (key, value) pairs, where values are arbitrary,
Or equivalently, Every Foo can have one value for every single key.
</edit>
As there's limited number of keys in FooOption, I'd like to rephrase this relation a bit using Django's ORM. The current design pictures the relation as a 1-n between a Foo and FooOptions; I'd like the code to picture it as 1-1 between a Foo and each specific FooOption key.
This would allow me to access each options like this:
class Foo(models.Model):
# ...
opt1 = OptionField('colour')
opt2 = OptionField('size')
foo = Foo()
foo.opt1 = 'something'
foo.save()
Especially, I'd like to be able to select_related specific FooOptions when querying for many Foos, to obtain an ORM-ed equivalent of:
SELECT foo.*, opt_colour.value, opt_size.value
FROM foo
LEFT JOIN foo_option opt_colour
ON foo.id = foo_option.foo_id AND foo_option.key = 'id'
LEFT JOIN foo_option opt_size
ON foo.id = foo_option.foo_id AND foo_option.key = 'size';
Is it possible to code such custom OptionField? How?
I may be misinterpreting your design, but it looks like you should actually be going with a Many-to-many relationship. You seem to want to have multiple options for each Foo instance (i.e. colour, size, etc.) and I imagine you would want a specific colour or size to be available to describe various Foo's.
class Foo(models.Model):
options = models.ManyToManyField('FooOption')
# Other attributes.
class FooOption(models.Model):
key = models.CharField(max_length=64)
value = models.TextField()
class Meta:
unique_together = [('key', 'value')]
I'm following the method used by #Yauhen Yakimovich in this question:
do properties work on django model fields?
To have a model field that is a calculation of a different model.
The Problem:
FieldError: Cannot resolve keyword 'rating' into field. Choices are: _rating
The rating model field inst correctly hidden and overridden by my rating property causing an error when I try to access it.
My model:
class Restaurant(models.Model):
...
...
#property
def rating(self):
from django.db.models import Avg
return Review.objects.filter(restaurant=self.id).aggregate(Avg('rating'))['rating__avg']
Model in Yauhen's answer:
class MyModel(models.Model):
__foo = models.CharField(max_length = 20, db_column='foo')
bar = models.CharField(max_length = 20)
#property
def foo(self):
if self.bar:
return self.bar
else:
return self.__foo
#foo.setter
def foo(self, value):
self.__foo = value
Any ideas on how to correctly hid the rating field and define the #property technique?
Solved by using sorted()
I was using a query with order_by() to call rating. order_by() is at the database level and doesnt know about my property. Soultion, use Python to sort instead:
sorted(Restaurant.objects.filter(category=category[0]), key=lambda x: x.rating, reverse=True)[:5]
If you encounter a similar error check through your views for anything that might be calling the property. Properties will no longer work at the datatbase level.
Change this line:
self._rating = Review.objects.filter(restaurant=self.id).aggregate(Avg('rating'))['rating__avg']
into this one:
self._rating = Review.objects.filter(restaurant=self.id).aggregate(Avg('_rating'))['_rating__avg']
(notice change of reference in query from rating and rating__avg to _rating and _rating__avg)