On Monday, 3 October 2011 14:42:36 UTC+1, Victor Hooi wrote:
>
> heya,
>
> I'm coding up a Django form which will let the user upload a CSV file, then 
> create and save multiple Model instances for each row in the CSV file.
>
> At the moment, I'm trying to decide where to put the code that parses the 
> CSV file and creates/saves the models.
>
> I don't think it'd be an instance method on the Model itself, since that's 
> for working on individual instances, and you'd need to pass a valid instance 
> to the method.
>
> Would it go in a custom Model Manager? Or should I have this logic in the 
> View itself?
>
> Also, I need to figure out a good way of passing ValidationErrors from the 
> model.save() and passing them back to the view to display the user.
>
> What would be a good way of hooking that up?
>
> Cheers,
> Victor
>

You could put it in the Manager, certainly - 
MyModel.objects.from_csv(filename) would be fine.

An alternative is to use a classmethod on the model, since that doesn't 
suffer from the drawbacks of the instance method:

    class MyModel(models.Model):
        @classmethod
        def from_csv(cls, filename):
            ...
            for row in csv:
                obj = cls(...)
                obj.save()

--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/MtPYfWSHlh4J.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to