django : unique name for object within foreign-key set

我只是一个虾纸丫 提交于 2019-12-12 19:38:00

问题


I'm trying to upload files for an article model. Since an object can have multiple images, I'm using a foreign-key from file model to my article model. However, I want all the files to have unique titles. Herez the code snippet.

class Article(models.Model):
    name = models.CharField(max_length=64)

class Files(models.Model):
    title = models.CharField(max_length=64)
    file = models.FileField(upload_to="files/%Y/%m/%d/")
    article = models.ForeignKey(Article)

Now when I upload the files, I want the file titles to be unique within the "foreign_key" set of Article, and NOT necessarily among all the objects of Files. Is there a way I can automatically set the title of Files? Preferably to some combination of related Article and incremental integers!! I intend to upload the files only from the admin interface, and Files are set Inline in Article admin form.


回答1:


def add_file(request, article_id):            
    if request.method == 'POST':  
        form = FileForm(request.POST, request.FILES)  
        if form.is_valid():  
            file = form.save(commit=False)  
            article = Article.objects.get(id=article_id)  
            file.article = article  
            file.save()  
            file.title = article.name + ' ' + file.id  
            file.save()  
            redirect_to = 'redirect to url'  
            return HttpResponseRedirect(redirect_to)      


来源:https://stackoverflow.com/questions/3932969/django-unique-name-for-object-within-foreign-key-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!