Reputation: 2570
I want to save some dates as a list in a Django model and can't get it done properly. So first I tried last_visits = CharField(....)
and wrote a function to add values to that Charfield. This did not work since I couldn't make a proper list.I found this(JSONField model attribute for lists), but storing python time into JSON will make problems since Json can't serialize it properly and converting it to str
would cause new problems since I would have to convert it back later.
So my question is: Is there an easy way to save multiple dates(list/array)?
someList = list()
global someList
def logins(self):
someList.append(datetime.datetime.now())
return someList
Thats a function I wrote and it works fine but the values are not getting saved. How would I add the old values of the list and add a new one into a model attribute (Charfield/textField/JSONField)?
I tried it like the following:
#"last_visit" is the model attribute
someList.append(self.last_visit)
self.last_visit += json.dumps(datetime.datetime.now())
self.last_visit = someList
self.last_visit.append(datetime.datetime.now())
self.last_visit.save()
but none of these worked. Please note that I didn't used all of these at once I just wanted to give an overview of what I tried.
Upvotes: 2
Views: 3317
Reputation: 603
I don't think that storing a list of date as char or text field is a good solution. Why don't you use model relations? I show you an example of model with an Event object that includes multiple related dates. Using a DateField is also convenient for filtering!!
class Event(models.Model):
name = models.CharField(max_length=255, unique=True, blank=False, null=False)
class EventData(models.Model):
event = models.ForeignKey(Event, on_delete=models.CASCADE)
date = models.DateField(default=None, blank=False, null=False)
Upvotes: 3