django-orm

How to implement followers/following in Django

谁都会走 提交于 2019-12-03 03:20:05
问题 I want to implement the followers/following feature in my Django application. I've an UserProfile class for every User (django.contrib.auth.User): class UserProfile(models.Model): user = models.ForeignKey(User, unique = True, related_name = 'user') follows = models.ManyToManyField("self", related_name = 'follows') So I tried to do this in python shell: >>> user_1 = User.objects.get(pk = 1) # <-- mark >>> user_2 = User.objects.get(pk = 2) # <-- john >>> user_1.get_profile().follows.add(user_2

Django Aggregation - Expression contains mixed types. You must set output_field

狂风中的少年 提交于 2019-12-03 03:12:21
I'm trying to achive an Aggregation Query and that's my code: TicketGroup.objects.filter(event=event).aggregate( total_group=Sum(F('total_sold')*F('final_price'))) I have 'total_sold' and 'final_price' in TicketGroup object and all what I want to do is sum and multiply values to get the total sold of all TicketGroups together. All I get is this error: Expression contains mixed types. You must set output_field What I am doing wrong, since I'm calling 'total_group' as my output field? Thanks! By output_field Django means to provide field type for the result of the Sum . from django.db.models

Is django prefetch_related supposed to work with GenericRelation

可紊 提交于 2019-12-03 01:04:41
UPDATE: An Open Ticked about this issue: 24272 What's all about? Django has a GenericRelation class, which adds a “reverse” generic relationship to enable an additional API . It turns out we can use this reverse-generic-relation for filtering or ordering , but we can't use it inside prefetch_related . I was wondering if this is a bug, or its not supposed to work, or its something that can be implemented in the feature. Let me show you with some examples what I mean. Lets say we have two main models: Movies and Books . Movies have a Director Books have an Author And we want to assign tags to

When does Django look up the primary key of foreign keys?

偶尔善良 提交于 2019-12-02 22:17:12
I have two simple models, one representing a movie an the other representing a rating for a movie. class Movie(models.Model): id = models.AutoField(primary_key=True) title = models.TextField() class Rating(models.Model): id = models.AutoField(primary_key=True) movie = models.ForeignKey(Movie) rating = models.FloatField() My expectation is that I would be able to first create a Movie and a Review referencing that movie then commit them both to the database, as long as I committed the Movie first so that it was given a primary key for the Review to refer to. the_hobbit = Movie(title="The Hobbit"

Django: Force select related?

纵饮孤独 提交于 2019-12-02 20:08:46
I've created a model, and I'm rendering the default/unmodified model form for it. This alone generates 64 SQL queries because it has quite a few foreign keys, and those in turn have more foreign keys. Is it possible to force it to always (by default) perform a select_related every time one of these models are returned? You can create a custom manager, and simply override get_queryset for it to apply everywhere. For example: class MyManager(models.Manager): def get_queryset(self): return super(MyManager, self).get_queryset().select_related('foo', 'bar') (Prior to Django 1.6, it was get_query

Annotating a Sum results in None rather than zero

瘦欲@ 提交于 2019-12-02 17:51:39
I'm making a QA site that is similar to the page you're on right now. I'm attempting to order answers by their score, but answers which have no votes are having their score set to None rather than 0. This results in answers with no votes being at the bottom of the page below negatively ranked answers. How can I make the annotated score be zero when there are no votes for an answer? Here's my model: from django.contrib.auth.models import User Answer(models.Model): //some fields here pass VOTE_CHOICES = ((-1, Down), (1, Up)) Vote(models.Model): user = models.ForeignKey(User) answer = models

Django database query: How to get object by id?

你。 提交于 2019-12-02 17:22:19
Django automatically creates an id field as primary key. Now I need to get the object by this id. object = Class.objects.filter() How to write this filter? iridescent If you want to get an object, using get() is more straightforward: obj = Class.objects.get(pk=this_object_id) I got here for the same problem, but for a different reason: Class.objects.get(id=1) This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected: Class.objects.all() Tail of the traceback for the get() method: File "django/db/models

How to implement followers/following in Django

不问归期 提交于 2019-12-02 16:49:36
I want to implement the followers/following feature in my Django application. I've an UserProfile class for every User (django.contrib.auth.User): class UserProfile(models.Model): user = models.ForeignKey(User, unique = True, related_name = 'user') follows = models.ManyToManyField("self", related_name = 'follows') So I tried to do this in python shell: >>> user_1 = User.objects.get(pk = 1) # <-- mark >>> user_2 = User.objects.get(pk = 2) # <-- john >>> user_1.get_profile().follows.add(user_2.get_profile()) >>> user_1.get_profile().follows.all() [<UserProfile: john>] >>> user_2.get_profile()

Django Queryset: Cast VARCHAR field in SQL before filtering

拟墨画扇 提交于 2019-12-02 12:58:05
问题 I have a table that I cannot control, but need to select from it. The field "building" is a varchar, and also defined like this in my (non managed) django model. But it should be treated as integer, when selecting from that table (there are values like "000100", and even spaces at the end). I need a simple filter like this: .annotate(CastInt("building")).filter(building__castint__exact=my_id) only problem is, CastInt does not exist. How could one achieve this? I was looking at .extra() (that

Comparing Object Fields with Django's ORM

﹥>﹥吖頭↗ 提交于 2019-12-02 07:54:25
Is comparing columns in different tables using less-than/greater-than operators supported in Django's ORM? For example, I'm trying to compare two object fields in a Django query, which would have the SQL equivalent of: SELECT a.id FROM mytable a LEFT OUTER JOIN myothertable b ON b.id = a.other_id AND a.val < b.someval Clearly, I can't use the normal filter() notation, since the RHS assumes the value is a literal, not an object/attribute name. e.g. MyTable.objects.filter(val__lt=other__someval) S.Lott's answer is the way to go. Here's an example of using F: class ModelA(models.Model): val =