简体   繁体   中英

django : unique name for object within foreign-key set

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.

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)      

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM