I am wondering if there is a design pattern or best practice to allow a Django-programmer to easily and safely get specific objects of a model.
Let me explain the question by an example:
I have a model with classes Pattern and Sequence.
class Pattern(models.Model):
name_id = models.CharField(max_length=50, unique=True)
sequence = models.CharField(max_length=50)
class Sequence(models.Model):
sequence = models.CharField(max_length=1000)
The database is initialized with several Patterns which will be used in methods that check for specific patterns within the objects of class Sequence. Let's say we build them like so:
Pattern.objects.create(name_id="the_a_pattern", sequence="DEF")
Pattern.objects.create(name_id="the_b_pattern", sequence="GF")
Now I want a safe way to get these Patterns when writing new code, without having to remember the exact id of the pattern. Instead of Pattern.objects.get(name_id='the_a_pattern')
I want to get help by Code Completion and use something like Pattern.get_the_a_pattern
. My first approach was to include get-methods in the model, but this will blow up the model very quickly and is not very well maintainable:
class Pattern(models.Model):
name_id = models.CharField(max_length=50, unique=True)
sequence = models.CharField(max_length=50)
@staticmethod
def get_the_a_pattern():
return Pattern.objects.get(name_id='the_a_pattern')
Since I couldn't find a good solution in the www, although I'm sure that this is a very common problem, I would appreciate any suggestions for a better design.
Aucun commentaire:
Enregistrer un commentaire