A
A
Altyn Bek2015-08-31 15:44:06
MySQL
Altyn Bek, 2015-08-31 15:44:06

How to get User.last_name in Django model as foreign key?

There are models in django app:

class News(models.Model):
    news_title = models.CharField(max_length=255, verbose_name="Заголовок поста")   # 3аголовок поста
    slug = models.SlugField(max_length=255, verbose_name="Идентификатор")    # Slug
    news_date = models.DateTimeField(u'Дата публикации')    # дата публикации u'Дата публикации'
    news_image = models.ImageField(upload_to='images/post_images', verbose_name="Изображение статьи")
    news_flickr_albumId = models.CharField(max_length=300, default="Нет фотографий", verbose_name="Flickr Album ID")
    news_content = models.TextField(max_length=20000,
                                    default="No content",
                                    verbose_name="Текст поста (максим 20000 симв)")   # текст поста
    news_author = models.ForeignKey(User, default='1', verbose_name="Автор статьи")   # Автор поста

    class Meta:
        ordering = ['-news_date', ]
        verbose_name = 'Новость'
        verbose_name_plural = 'Новости'

    def __unicode__(self):
        return self.slug

    def get_absolute_url(self):
        return "/news/%s/" % self.slug

As you noticed, news_author takes from User User.username, and this is not good in my opinion, I would like User.last_name.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-08-31
@altyn

1. As we noticed, news_author does not take from User User.username. The field is turned into news_author_id and User.pk (id) is taken from User. Taking last_name is stupid, because collisions are inevitable. Another thing is that you see username, because the user has return self.username in the __unicode__ method. To display what you want - use its own methods or attributes (get_full_name or last_name, as you want).
2. Why don't you feed the vast majority of bread - let me call attributes crooked? Why do attributes news_author, news_title, news_content if your model is ALREADY called News?
3.

def get_absolute_url(self):
        return "/news/%s/" % self.slug

This is bad. Deal with the reverse function (well, reverse_lazy) and the {% url %} template tag

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question