Reputation: 11039
I'm about to make a Django model with conditions. I've thought about these fields
class Condition(models.Model):
model_name = CharField(max_length=100)
field_name = CharField(max_length=100)
value = CharField(max_length=100)
So I can create a condition where a specific field (field_name
) in a specific model (model_name
) is equal to value
. But I thought there might be a solution for this already? Instead of using field_name
I thought if it was possible to refer directly to the field either through ContentType
or something else?
Upvotes: 1
Views: 98
Reputation: 279
I know this is very high level and the code does not exactly model what you were asking. But they are simple examples from a
Django Signals to determine when a change happened. https://docs.djangoproject.com/en/dev/topics/signals/
Here is a signals.py file in my app for managing Person objects when Users change:
from django.db import models
from anotherapp.models import *
def user_post_delete(sender, instance, **kwargs):
try:
if instance.username:
person_item = Person.objects.get(username = instance.username)
person_item.django_user = None
person_item.save()
except:
pass
def user_post_save(sender, instance, **kwargs):
try:
if instance.username:
p, created = Person.objects.get_or_create(
username=instance.username)
p.django_user = instance
p.save()
except:
pass
models.signals.post_delete.connect(user_post_delete, sender=User)
models.signals.post_save.connect(user_post_save, sender=User)
Django ContentTypes to relate your condition to the object in question. https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
Here is an model I am using with ContentTypes:
from django.contrib.contenttypes.models import ContentType
class Comment(models.Model):
message = models.TextField()
#removed fields not relevent
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
date_added = models.DateTimeField('date_added',auto_now_add=True, editable=False)
date_updated = models.DateTimeField('date_updated',auto_now_add=True, auto_now=True, editable=False)
Then in your views.py/signals.py to use that ContentType model(Ticket is a model name, and t.id is the id of the Ticket object:
new_comment = Comment(
message = "test message",
content_type = ContentType.objects.get(model='Ticket'),
object_id = t.id,
)
new_comment.save()
You would then want to expand to have a simple boolean as to if your condition was met, or get a bit more into it and use another model to store results and come up with a "5
Upvotes: 1