Hot answers tagged

11

1. Introduction By coincidence, I'm working on a similar problem right now, so here's a chance for me to write up an experiment I ran today, in the hope that it might prove useful. However, the solution presented below is far from ideal (see section 3). 2. The idea Processing your query results through Django's ORM and then through csv.writer is time-...


9

As an alternative to the answer given by jcollado, Django has some built in decorators to help. From the docs: from django.contrib.auth.decorators import user_passes_test def email_check(user): return '@example.com' in user.email @user_passes_test(email_check) def my_view(request): https://docs.djangoproject.com/en/1.6/topics/auth/default/#limiting-...


9

I've come back to this question about 4 or 5 times since it was originally posted, started writing up an answer, started doubting my alternative implementation, scrapped it, and then come back about a month later. This tells me a few things: You have a tricky problem, where the "best" solution is not necessarily intuitive, and how you measure "best" can ...


8

I'd say this is a good example on how to not use DB. The problem here is that for each keyword you will call a DB instead of perform this as a single call, so if you list of keywords is 1000 items then you will do 1000 calls to DB. You can avoid this by splitting your call to: 1. Get existing keywords existing_keywords = Keyword.objects.filter(...


7

1. Answers to your questions If the goal of the project is to be able to include Haml in attribute values, then you've got no choice but to switch to your own parser. I haven't looked at the set of test cases, but it does seem plausible that you are going to introduce incompatibilities because of the complexity of Python's own parser. You are going to find ...


7

Yes, this clever code solves your problem : you won't be able to nest commit_on_success or atomic under commit_on_success. You already know the caveats, but I'll repeat them anyway: If you do nest a block under a commit_on_success, your code will consistently fail: easy to fix as long as this code path is executed in your tests. It's always possible to ...


7

As mentioned in the comments, it would be useful if you included more than just the models here. As a result, I can only really do a design review of what appears to be a fairly generic quiz application. Right now your models are set up this way So exams can share questions, and questions can share answers. This is useful in cases where exams typically ...


7

Let's focus on the selecting. class MyPage(ListView): model = Post def get_queryset(self): posts = [] for user in self.request.user.followers.all(): for post in Post.objects.filter(author=user.followed): posts.append(post) return posts This is a bit convoluted: you're performing a lot of queries ...


7

From what I understand, the lru_cache is not the right tool when it comes to caching things in a production web application. Depending on how the web application is deployed, you would usually end up having multiple web server processes serving your application. Which means, that the LRU cache will be created in the memory space of every process. It's like ...


6

You should use the functools.wraps function, it makes sure the docstring/name/etc gets passed through Instead of "ajax not supported" shouldn't it be: "only ajax supported"? Shouldn't you respond with a Status Code 400 or something if not using ajax when you should be Why do you want to check this? What's the point of enforcing ajax calls, won't that just ...


6

In addition to logic, which Janne's answer covered, here is some style analysis (which is an important part of writing good code): First - it's nice to have a good docstring, with all the information about the function - what does it do, what does it take, what it returns. from operator import itemgetter This can be a matter of opinion, but it's a good ...


6

Tuples are sorted primarily by the first item of each. If they are all unique, specifying key=itemgetter(0) makes no difference. This code if prefix == 0: etuples = sorted([(k,v) for k,v in items if k[:2] == 'e_'], key=itemgetter(0)) ituples = sorted([(k,v) for k,v in items if k[:2] == 'i_'], key=itemgetter(0)) tuples = etuples+ituples ...


6

Firstly, you should raise not return your errors. Secondly, try: with a bare except: is bad practice (e.g. http://blog.codekills.net/2011/09/29/the-evils-of--except--/); what do you expect could go wrong with each step? Test for specific errors and deal with them appropriately. It is this which has hidden the NameError I mention at the end. Thirdly, your ...


6

One thing that concerns me about this approach is that Applicant is huge. I'd consider splitting this into a few different models. At the very least I'd imagine that I'd want to split out the details for a person and contact information: class Person(models.Model): """Information for a person""" first_name=models.CharField('Nombres',max_length=30) ...


6

Few things here: 1. Parent1 and Parent2 It's not really clear why would you need to have parents in the separate tables while they both represent a person. There is no difference between parent1 and parent2 so they can be stored in the same table. 2. Parent1/Parent2/BirthCertificate They all share lots of common fields, so you can create an abstract class ...


6

The good So, you're trying to allow users to create new questions, but those questions must have a slug which is unique. You're enforcing this on the database level with unique=True, which is a good start. You are using a form to handle the creation of new questions, which is definitely the right way to do this. It'll also be really useful when you need to ...


5

Why are you importing everything directly in this way? That's what's causing your problem. You realise that you can just call something like import django.utils and then still get access to all these things. I'm not familiar with django specifically, but most modules and packages can be imported with a plain import, like import django and then accessed. But ...


5

In general this seems fine, easy to read, you seem to be following PEP8, that's excellent. At first look, this repeated logic in balance and debt jumps in the eye: @property def balance(self): # ... while current_date <= today: result -= sum(x.total for x in self.cashing_set.on_date(current_date)) result -= sum(x.total for x in ...


5

Here is my alternative. Your original code calls the DB for the same record twice (potentially) -- the get_or_create does the same as your try/except and creates the record. def save_number(request): from_number = request.POST.get('From', '') subscribe = request.POST.get('Body', '').lower().strip() obj, created = SaveNumber.objects....


5

When you don't need indexes or ordering, it is generally a good idea to use a set over a list because its membership testing is more efficient. That means, use nums = set() instead of nums = [], and use nums.add(...) instead of nums.append(...). That's all you need to change. I'm not sure why you are accessing the special method directly. Why not use ...


5

Don't reinvent the wheel Since you're handling a security feature, you shouldn't roll your own. As often with python, Django comes bateries included. And since they already need to generate random passwords (when prepopulating SECRET_KEY for instance), chances are they already have a more secure way of doing. Indeed, django.utils.crypto.get_random_string() ...


5

The usual "django" way of doing this - is to use get_app_config() function to get the AppConfig instance, then call .get_models() method: from django.apps import apps app = apps.get_app_config('auth') for model in app.get_models(): admin.site.register(model)


5

Dicts are good for lookups When encountering stacked ifs that are all alike, I tend to pickup a dict and try to put it to good use. One way to structure the variable parts of your routine is with something like: user_form_types = { UserProfile.INSURANCE_BROKER: InsuranceBrokerForm, UserProfile.AUTO_DEALERSHIP: AutoDealershipForm, UserProfile....


5

Try this: def generate_func(url_attr, type_class, source_type): def f(self, scan_id): for keyword in type_class.objects.all(): self.process_rss_url(getattr(keyword, url_attr), source_type, keyword.id, keyword.last_scan_time, scan_id) keyword.last_scan_time = timezone.now() keyword.save() return f ...


5

There's a lot of duplication here for like items. A sign that loops and templates will reduce redundancy. There's a few distinct steps here. Better to separate each step to separate concerns. For example, there's 1. creating the payload 2. creating the CI, 3. describing what was created. It looks like you can re-use UsdDBActions. If so, it would be better to ...


5

We can learn a lot about what code is supposed to do by giving our functions explicit type signatures. Starting at the top, what are we working with? team_id is some kind of Team ID. It's probably a string, or maybe an int, but for now I'll assume it's a TeamID. We know it's exactly what we need because it's passed as-is to the Django filters an SlackUser....


4

Since posting this question I have rewritten the code completely. However, to solve this particular issue, one could rewrite: if model == Image: star_media = rel_object.star_image else: star_media = rel_object.star_video to star_media = model.get_star_media(rel_object) get_star_media would be class method of Video and Image models (defined as ...


4

Formatting I think your query could really use some white space to make it easier to read. I realize there is no official standard for SQL, but here is my preferred style: SELECT "odds_odds"."id", "odds_odds"."offer_id", "odds_odds"."time", "odds_odds"."o1", "odds_odds"."o2", "odds_odds"."o3", "odds_odds"."o4", MAX(...


4

This can be radically simpler and faster with the Postgres specific DISTINCT ON: SELECT DISTINCT ON (offer_id) offer_id, id, time, o1, o2, o3, o4, time -- or just * to include all columns FROM odds_odds ORDER BY offer_id, time DESC; You don't need to touch the table odds_offer at all. Note that you only get odds of offers that have at least one ...


4

ast.literal_eval(...) If we can remove your calls to ast.literal_eval(...) we should see a nice reduction in the run time of your loops. But, why can we remove this you ask? Consider: m = '[0, 1, 2, ... , 9,999]' # a str representation of list w/ 10k elements, 0-9999 n = '[0, 1, 2]' x = ast.literal.eval(m) y = ast.literal.eval(n) x == ...


Only top voted, non community-wiki answers of a minimum length are eligible